I've already searched for the answer, and there are a few for this type of issue but not that I can get to work. What I am trying to setup is probably best explained if you use the code below and try it yourself, but I'll try to explain myself.
I have several input fields which are cloned after they have data inputted into them. Now I am trying to integrate an autocomplete script with it. So that all the one has to do is type the name of a person, select it from the popup and it puts the data into the cells.
The issue is that it won't input data for anything but the initial row, because the cloner changes the id by increasing the id number everything its cloned. Can anyone point me in the right direction of how to increment the autocompleter? Or how to rerun for each clone?
Thanks everyone, and here are the files needed to replicate the issue.
SQL
-- Table structure for table `employees`
--
CREATE TABLE IF NOT EXISTS `employees` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`fname` varchar(50) NOT NULL,
`lname` varchar(50) NOT NULL,
`wage` int(12) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `employees`
--
INSERT INTO `employees` (`id`, `fname`, `lname`, `wage`) VALUES
(1, 'John', 'Doe', 25),
(2, 'Bob', 'Smith', 30);
test.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
//cloning script
$("#employee input").live("keyup", function(){
var id = this.id.match(/\d+/);
});
// The second requirement:
var uniqueIds = $("#employee tr").length;
$("#employee input[id^='employee_fname']").live("change", function(){
var $thisRow = $(this).closest("tr"),
$clone = $thisRow.clone(true), // Clone row
$inputs = $clone.find("input").val("");// Reset values, return all inputs
uniqueIds++; //Increment ID
$inputs[0].id = "employee_id" + uniqueIds;
$inputs[1].id = "employee_fname" + uniqueIds;
$inputs[1].id = "employee_lname" + uniqueIds;
$inputs[2].id = "employee_wage" + uniqueIds;
//$inputs.eq(0).focus(); // Focus on the first text field
$thisRow.after($clone); // Add row after current one
});
</script>
<script>
//autosuggest script
function lookup(employee_fname) {
if(employee_fname.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("test_ac.php", {queryString: ""+employee_fname+""},function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill1(thisValue) {
$('#employee_fname').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
function fill2(thisValue) {
$('#employee_id').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
function fill3(thisValue) {
$('#employee_lname').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
function fill4(thisValue) {
$('#employee_wage').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
<style>
.suggestionsBox {
position: relative;
left: 30px;
margin-top:100px;
margin-left:-35px;
margin-right:0px;
margin-bottom:0px;
padding:0px;
width: 150px;
background-color: #212427;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #000;
color: #fff;
}
.suggestionList {
margin: 0px;
padding: 0px;
}
.suggestionList li {
margin: 0px 0px 3px 0px;
padding: 3px;
cursor: pointer;
}
.suggestionList li:hover {
background-color: #659CD8;
}
</style>
</head>
<body>
<table>
<tr>
<td width="200">
<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</td>
<td>
<table>
<tr>
<td width="120" align="left" style="width:120px;">ID</td>
<td width="120" align="left" style="width:120px;">First Name</td>
<td width="120" align="left" style="width:120px;">Last Name</td>
<td width="120" align="left" style="width:120px;">Wage</td>
</tr>
</table>
<table id="employee">
<tr>
<td align="left"><input type="text" id="employee_id" name="employee_id" style="width:100px; background-color:#e5e5e5;" readonly="readonly" onblur="fill2();"/></td>
<td align="left"><input type="text" id="employee_fname" name="employee_fname" style="width:100px;" onblur="fill1();" onkeyup="lookup(this.value);"/></td>
<td align="left"><input type="text" id="employee_lname" name="employee_lname" style="width:100px; background-color:#e5e5e5;" readonly="readonly" onBlur="fill3"/></td>
<td align="left"><input type="text" id="employee_wage" name="employee_wage" style="width:100px; background-color:#e5e5e5;" readonly="readonly" onblur="fill4();" /></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
test_ac.php
<?php
// PHP5 Implementation - uses MySQLi.
// mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
$db = new mysqli('localhost', 'root' ,'passsword', 'database');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
// Run the query: We use LIKE '$queryString%'
// The percentage sign is a wild-card, in my example of countries it works like this...
// $queryString = 'Uni';
// Returned data = 'United States, United Kindom';
// YOU NEED TO ALTER THE QUERY TO MATCH YOUR DATABASE.
// eg: SELECT yourColumnName FROM yourTable WHERE yourColumnName LIKE '$queryString%' LIMIT 10
$query = $db->query("SELECT fname, lname, id, wage FROM employees WHERE fname LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
// YOU MUST CHANGE: $result->value to $result->your_colum
echo '<li onClick="fill1(\''.$result->fname.'\');
fill2(\''.$result->id.'\');
fill3(\''.$result->lname.'\');
fill4(\''.$result->wage.'\');
">'.$result->lname. ',' .$result->fname.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>
Change the autosuggest script to the code below. This solved my issue.
var sourceElement;
//autosuggest script
function lookup2(source, employee_id) {
sourceElement = source;
if(employee_id.length == 0) {
// Hide the suggestion box.
$('#suggestions2').hide();
} else {
$.post("../../autocomplete/jobadd_employee.php", {queryString: ""+employee_id+""},function(data){
if(data.length >0) {
$('#suggestions2').show();
$('#autoSuggestionsList2').html(data);
}
});
}
} // lookup
function fill8(thisValue) {
$('#employee_id'+sourceElement.id.replace("employee_id","")).val(thisValue);
setTimeout("$('#suggestions2').hide();", 200);
}
function fill9(thisValue) {
$('#employee_fname'+sourceElement.id.replace("employee_id","")).val(thisValue);
setTimeout("$('#suggestions2').hide();", 200);
}
function fill10(thisValue) {
$('#employee_lname'+sourceElement.id.replace("employee_id","")).val(thisValue);
setTimeout("$('#suggestions2').hide();", 200);
}
function fill11(thisValue) {
$('#employee_wage'+sourceElement.id.replace("employee_id","")).val(thisValue);
setTimeout("$('#suggestions2').hide();", 200);
}
Related
I have a paypal Smart Button on my WordPress site:
https://baranovich.org/pay-for-auction-purchase/
The code is from PayPal and I edited it a little because the input fields were not displaying properly.
When I use the button, everything seems fine, but then I can't pay by logging into another account.
It just doesn't log in. It doesn't give me an error either.
After I enter the email it goes back to here but I haven't logged in...
I tied clearing the cache, and used different browsers and PCs.
I checked out the answer https://stackoverflow.com/questions/53840252/unable-to-login-to-paypal-using-paypal-payment-button-localhost
But I don't understand why I'm even using the sandbox PayPal feature. I wanted a real button, not a sandbox test button...
How do I put a real PayPal button?
Here is the code I am using:
<style>
input {
border-top-style: hidden;
border-right-style: hidden;
border-left-style: hidden;
border-bottom-style: groove;
background-color: #eee;
}
</style>
<div id="smart-button-container">
<div style="text-align: center">
<label for="description">First and Last Name </label>
<span style="display:inline-block; width:10px;"></span>
<input type="text" name="descriptionInput" id="description" maxlength="127" value=""></div>
<p id="descriptionError" style="visibility: hidden; color:red; text-align: center;">Please enter a First and Last Name</p>
<div style="text-align: center"><label for="amount">Amount to Pay </label>
<span style="display:inline-block; width:10px;"></span>
<input name="amountInput" type="number" id="amount" value="" ><span> USD</span></div>
<p id="priceLabelError" style="visibility: hidden; color:red; text-align: center;">Please enter the full amount owed</p>
<div id="invoiceidDiv" style="text-align: center; display: none;"><label for="invoiceid">Auction Lot Number </label>
<span style="display:inline-block; width:10px;"></span>
<input name="invoiceid" maxlength="127" type="text" id="invoiceid" value="" ></div>
<p id="invoiceidError" style="visibility: hidden; color:red; text-align: center;">Please enter the Lot number</p>
<div style="text-align: center; margin-top: 0.625rem;" id="paypal-button-container"></div>
</div>
<script src="https://www.paypal.com/sdk/js?client-id=sb&enable-funding=venmo¤cy=USD" data-sdk-integration-source="button-factory"></script>
<script>
function initPayPalButton() {
var description = document.querySelector('#smart-button-container #description');
var amount = document.querySelector('#smart-button-container #amount');
var descriptionError = document.querySelector('#smart-button-container #descriptionError');
var priceError = document.querySelector('#smart-button-container #priceLabelError');
var invoiceid = document.querySelector('#smart-button-container #invoiceid');
var invoiceidError = document.querySelector('#smart-button-container #invoiceidError');
var invoiceidDiv = document.querySelector('#smart-button-container #invoiceidDiv');
var elArr = [description, amount];
if (invoiceidDiv.firstChild.innerHTML.length > 1) {
invoiceidDiv.style.display = "block";
}
var purchase_units = [];
purchase_units[0] = {};
purchase_units[0].amount = {};
function validate(event) {
return event.value.length > 0;
}
paypal.Buttons({
style: {
color: 'gold',
shape: 'pill',
label: 'paypal',
layout: 'horizontal',
},
onInit: function (data, actions) {
actions.disable();
if(invoiceidDiv.style.display === "block") {
elArr.push(invoiceid);
}
elArr.forEach(function (item) {
item.addEventListener('keyup', function (event) {
var result = elArr.every(validate);
if (result) {
actions.enable();
} else {
actions.disable();
}
});
});
},
onClick: function () {
if (description.value.length < 1) {
descriptionError.style.visibility = "visible";
} else {
descriptionError.style.visibility = "hidden";
}
if (amount.value.length < 1) {
priceError.style.visibility = "visible";
} else {
priceError.style.visibility = "hidden";
}
if (invoiceid.value.length < 1 && invoiceidDiv.style.display === "block") {
invoiceidError.style.visibility = "visible";
} else {
invoiceidError.style.visibility = "hidden";
}
purchase_units[0].description = description.value;
purchase_units[0].amount.value = amount.value;
if(invoiceid.value !== '') {
purchase_units[0].invoice_id = invoiceid.value;
}
},
createOrder: function (data, actions) {
return actions.order.create({
purchase_units: purchase_units,
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (orderData) {
// Full available details
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
// Show a success message within this page, e.g.
const element = document.getElementById('paypal-button-container');
element.innerHTML = '';
element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
},
onError: function (err) {
console.log(err);
}
}).render('#paypal-button-container');
}
initPayPalButton();
</script>
Sandbox buttons can only be logged into with a sandbox payer account from the developer dashboard.
Since you want a live button, you'll need to regenerate it when logged into your live PayPal account that you want to receive the payments. Alternatively, manually change the code that says client-id=sb to use a live client ID from a live REST App, which are created in the developer dashboard -> My Apps & Credentials.
I want to bind to list of strings with ability to add new item or delete existing, similar to the UI in Azure DevOps -> Process -> Edit Work Item type... it has an a add text box/button at the top, the list of items, and the ability to delete each item with an X.
I tried to look at the html code but it seems dynamically created with javascript. Any existing solution so i don't need to reinvent the wheel? Thank you
According to your description, when the cursor focuses on the input text element, it will show the select items, and might be it implement the autocomplete function.
To achieve this effect, first, you should use JQuery Ajax to get the selectable items from the controller, then, you could attach the focusin, input and keydown events on the input text element, in these events, you could according to the entered value to add html elements, in order to show/hide the select item.
For the delete icon on each select option, you could use the Font Awesome element, and attach the click event to achieve the delete action.
Finally, to achieve the add new value feature, you could use the Bootstrap Modal to show a popup modal and insert the new value.
More detail steps, you could check the following sample code:
Controller:
//main page
public IActionResult SelectIndex()
{
return View();
}
//this method is used to get the select items.
[HttpGet]
public IActionResult GetSelectItems()
{
//initial data. You could query database and get the real data.
List<string> list = new List<string>() { "Angola", "Anguilla", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Cambodia", "Cameroon", "Canada", "Dominica", "Dominican Republic", "Ecuador", "Egypt" };
return Json(list);
}
View page (SelectIndex.cshtml):
CSS style:
<style>
* {
box-sizing: border-box;
}
body {
font: 16px Arial;
}
/*the container must be positioned relative:*/
.autocomplete {
position: relative;
display: inline-block;
}
input {
border: 1px solid transparent;
background-color: #f1f1f1;
padding: 10px;
font-size: 16px;
}
input[type=text] {
background-color: #f1f1f1;
width: 100%;
}
input[type=submit] {
background-color: DodgerBlue;
color: #fff;
cursor: pointer;
}
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
z-index: 99;
/*position the autocomplete items to be the same width as the container:*/
top: 100%;
left: 0;
right: 0;
}
.autocomplete-items div {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
/*when hovering an item:*/
.autocomplete-items div:hover {
background-color: #e9e9e9;
}
/*when navigating through the items using the arrow keys:*/
.autocomplete-active {
background-color: DodgerBlue !important;
color: #ffffff;
}
</style>
main html resource:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
<i class="fa fa-plus"></i> Add Value
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add a New Value</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<input id="inputNewValue" type="text" placeholder="Enter a new Country">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnAddNew" data-dismiss="modal">Submit</button>
</div>
</div>
</div>
</div>
</form>
JavaScript script:
<script>
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when focus on the text field*/
inp.addEventListener("focusin", function () {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { arr = countries.slice(0, 5); }
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
b.innerHTML += "<span style='font-size: 1em; color: Tomato; float: right'><i class='fa fa-times'></i></span>"
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function (e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
b.getElementsByTagName("span")[0].addEventListener("click", function (e) {
e.stopPropagation();
var deletevalue = this.parentElement.getElementsByTagName("input")[0].value;
//delete item from the data array.
const index = countries.indexOf(deletevalue);
if (index > -1) {
countries.splice(index, 1);
}
//remove item from current
document.getElementsByClassName("autocomplete-items")[0].removeChild(this.parentElement);
//closeAllLists(e.target);
autocomplete(document.getElementById("myInput"), countries.sort());
});
a.appendChild(b);
}
}
});
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function (e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) {return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
b.innerHTML += "<span style='font-size: 1em; color: Tomato; float: right'><i class='fa fa-times'></i></span>"
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function (e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
b.getElementsByTagName("span")[0].addEventListener("click", function (e) {
e.stopPropagation();
var deletevalue = this.parentElement.getElementsByTagName("input")[0].value;
//delete item from the data array.
const index = countries.indexOf(deletevalue);
if (index > -1) {
countries.splice(index, 1);
}
//remove item from current
document.getElementsByClassName("autocomplete-items")[0].removeChild(this.parentElement);
//closeAllLists(e.target);
autocomplete(document.getElementById("myInput"), countries.sort());
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function (e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
/*An array containing all the country names in the world:*/
// var countries = ["Angola", "Anguilla", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Cambodia", "Cameroon", "Canada", "Dominica", "Dominican Republic", "Ecuador", "Egypt"];
var countries;
$.get("/Home/GetSelectItems", function (response) {
countries = response;
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
autocomplete(document.getElementById("myInput"), countries.sort());
})
document.getElementById("btnAddNew").addEventListener("click", function (e) {
var newvalue = document.getElementById("inputNewValue").value;
var itemindex = countries.indexOf(newvalue);
if (itemindex == -1) {
countries.push(newvalue);
}
autocomplete(document.getElementById("myInput"), countries.sort());
});
</script>
The result like this (when focus on the input element, it will show the Top 5 items):
I have an issue and want to see if this thought is possible. I created a project tracker where an individuals can load their project information (office, project title, status, date, assigned to., etc). The form works great. I have another form, update form, for the individual to update their input value (choice same as load project form: office, project, title, status, date, assigned to., etc) as the project progress. This form updates great. However, a issue I am having, if the HTML field is left blank, on the update form HTML input field, it sends a value of “null” that overrides the value posted to the tracker list of post - not being updated. The update form intended purpose is to give the individual a list of possible choices to what they might need to update, in this case everything.
Is there a way to not send any value if the input field is left blank to not override the value currently posted? Is this even possible or do I need to do something different, like have a separate update form for each different area/column being updated.
I am posting and updating the values to a SharePoint using the REST API.
---Edit to include Script---
<div id="container">
<!-- --------------- code to update a list item ------------- -->
<div id="updateForm">
<div id="UpdateClose" style='text-align: left; float: right; margin-right: 10px; cursor: pointer;'>Close</div>
<div style='margin: 0 auto; width: 100%; padding-top: 5px; padding-bottom: 5px; color: white; margin-top: 40px; margin-bottom: 10px; background-color: orange;'>
<p>Click here to move</p>
</div>
<p>Fill out this form completely to update your item.</p>
<input placeholder="Item ID" type="text" id="itemID">
<table>
<tr>
<td>Office</td>
<td><input type="text" id="uOffice" style="width: 200px"></td>
</tr>
<tr>
<td>Project Title</td>
<td><input type="text" id="uProjectTitle" style="width: 200px"></td>
</tr>
<tr>
<td>Priority</td>
<td><input type="text" id="uPriority" style="width: 200px"></td>
</tr>
<tr>
<td>Start Date</td>
<td><input type="text" id="uStartDate" style="width: 200px"></td>
</tr>
<tr>
<td>Assigned To</td>
<td><input type="text" id="uAssignedTo" style="width: 200px"></td>
</tr>
<tr>
<td>Status</td>
<td><input type="text" id="uStatus" style="width: 200px"></td>
</tr>
<tr>
<td>Requestor</td>
<td><input type="text" id="uRequestor" style="width: 200px"></td>
</tr>
</table>
<button id="UpdateListItem">UPDATE</button>
</div>
<div id="introTxt">
<p>Post and Track your Projects</p>
<p id='openForm'><img class='qIcon' src="https://intelshare.intelink.gov/sites/dcsa/ep/epMainFiles/Project_Tracker/graphics/google-docs.svg" alt="logo" style="width: 100px; position: relative; top: 0px; margin-right: 10px; cursor: pointer; "><span style='color: blue; cursor: pointer; position: relative; top: 20px; font-weight: bold;' >Select to post a project. When the post project form opens, hover over the input fields for additional instructions.</span></p>
<p id='openUForm'><img class='qIcon' src="https://intelshare.intelink.gov/sites/dcsa/ep/epMainFiles/Project_Tracker/graphics/google-docs.svg" alt="logo" style="width: 100px; position: relative; top: 0px; margin-right: 10px; cursor: pointer; "><span style='color: black; cursor: pointer; position: relative; top: 20px; font-weight: bold;' >Select to update a task. When the post project form opens, hover over the input fields for additional instructions.</span></p>
</div>
<div id="qForm" style='width: 250px; height: auto; padding: 10px; position: absolute; z-index: 10; background-color: white; border: 1px solid grey; text-align:center; cursor: all-scroll; display: none;'>
<div id="qFormClose" style='text-align: left; float: right; margin-right: 10px; cursor: pointer;'>Close</div>
<div style='margin: 0 auto; width: 100%; padding-top: 5px; padding-bottom: 5px; color: white; margin-top: 40px; margin-bottom: 10px; background-color: orange;'>
<p>Click here to move</p>
</div>
<input type="text" placeholder="Enter Your Office" name="Office" id="office" title='Enter in your office' required> <br><br>
<input type="text" placeholder="Enter a Project Name" name="Project Name" id="project" title='Enter in a project name' required> <br><br>
<input type="text" placeholder="Priority" name="url" id="priority" title='Enter in project priority'> <br><br>
<input type="text" placeholder="Project Start Date" name="Start Date" id="startDate" title='Enter in project start date'> <br><br>
<input type="text" placeholder="Assigned to" name="Assigned" id="assigned" title='Project assigned to'> <br><br>
<input type="text" placeholder="Status" name="Status" id="status" title='Project status'> <br><br>
<input type="text" placeholder="Requestor" name="Requestor" id="requestor" title='Project requestor'> <br><br><br>
<div id="udList" style='cursor: pointer';>Submit</div>
</div>
<div class="row vertical-padding"></div>
<!--Close of vertical padding-->
<div id="leftCol" class="grid_12">
<input id="myInput" type="text" placeholder="To find a specific task, enter either the office name, individual's name, or by task ID...">
<h2 style='color:blue; marigin: 0 auto; text-align: center; font-weight: bold;'>Project List</h2>
<p>Select table header to sort.</p>
<div id="CustomerPanel">
<table id='tableCars' style="width: 100%;" border="1 px">
<tr>
<td>
<div id="carsGrid" style="width: 100%"></div>
</td>
</tr>
</table>
</div>
</div>
<!--Close of grid-->
</div>
<!--Close container-->
/*Add to Project Tracker List*/
var context;
var web;
var Url;
var listItemEntity;
jQuery(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', FunctionReady);
ItemSubmit();
$("#qForm").draggable();
$("#qFormClose").click(function() {
$("#qForm").fadeOut();
});
$("#openForm").click(function() {
$("#qForm").fadeIn();
});
$("#openUForm").click(function() {
$("#updateForm").fadeIn();
});
}); //Close of document ready function
var answer = document.getElementById('comAnswer');
function ItemSubmit() {
$("#udList").click(function() {
$("#qForm").fadeOut(400);
var officeValue = $("#office").val();
var projectValue = $("#project").val();
var priorityValue = $("#priority").val();
var startDateValue = $("#startDate").val();
var assignedValue = $("#assigned").val();
var statusValue = $("#status").val();
var requestorValue = $("#requestor").val();
if (this.value != 0) {
AddItemToList(listItemEntity, officeValue, projectValue, priorityValue, startDateValue, assignedValue, statusValue, requestorValue);
} else {
AddItemToList(listItemEntity, officeValue, projectValue, priorityValue, startDateValue, assignedValue, statusValue, requestorValue);
}
$('#qForm').children('input').val('');
});
}
function FunctionReady() {
context = new SP.ClientContext.get_current();
web = context.get_web();
context.load(web);
context.executeQueryAsync(onRequestSuccess, onRequestFailure);
}
function onRequestSuccess() {
Url = web.get_url();
GetListItemEntity(Url);
}
function onRequestFailure(sender, args) {
alert("Error Occured:" + args.get_message());
}
function GetListItemEntity(webUrl) {
var queryUrl = webUrl + "/_api/lists/getbytitle('ProjectTracker')?$select=ListItemEntityTypeFullName";
$.ajax({
url: queryUrl,
method: "GET",
headers: {
"Accept": "application/json;odata=verbose"
},
success: onEntitySuccess,
error: onEntityFailure
});
}
function onEntitySuccess(data) {
listItemEntity = data.d.ListItemEntityTypeFullName;
}
function onEntityFailure(err) {
alert(err.statusText);
}
function AddItemToList(r, officeValue, projectValue, priorityValue, startDateValue, assignedValue, statusValue, requestorValue) {
try {
var queryUrl = Url + "/_api/lists/GetByTitle('ProjectTracker')/items?";
$.ajax({
url: queryUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
'__metadata': {
'type': r
},
'Office': officeValue,
'ProjectTitle': projectValue,
'Priority': priorityValue,
'StartDate': startDateValue,
'AssignedTo': assignedValue,
'Status': statusValue,
'Requestor': requestorValue
}),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucess,
error: onQueryFailure
});
} catch (ex) {
alert("Exception" + ex.message);
}
}
function onQuerySucess() {
jQuery("#success").fadeIn();
}
function onQueryFailure(error) {
alert(JSON.stringify(error));
}
jQuery(document).ready(function() {
////Project Tracker Table script
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ProjectTracker')/items";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="projectTable" style="width:100%" border="1 px"><thead><th>ID</th>' + '<th>Office</th>' + '<th>Project_Title</th>' + '<th>Project_Priority</th>' + '<th>Project_Date</th>' + '<th>Assigned_To</th>' + '<th>Project_Status</th>' + '<th>Requestor</th>' + '</thead><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr class="sortTable">';
tableContent += '<td>' + objItems[i].ID + '</td>';
tableContent += '<td>' + objItems[i].Office + '</td>';
tableContent += '<td>' + objItems[i].ProjectTitle + '</td>';
tableContent += '<td>' + objItems[i].Priority + '</td>';
tableContent += '<td>' + objItems[i].StartDate + '</td>';
tableContent += '<td>' + objItems[i].AssignedTo + '</td>';
tableContent += '<td>' + objItems[i].Status + '</td>';
tableContent += '<td>' + objItems[i].Requestor + '</td>';
tableContent += '</tr>';
}
$('#projectGrid').append(tableContent);
}
function onError(error) {
alert('Error');
}
}); ///End of Document Ready Function
///Sort Project Table
jQuery(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$(".sortTable").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
jQuery(document).on("click", 'th', function() {
if ($(this).is('.asc')) {
$(this).removeClass('asc');
$(this).addClass('desc selected');
sortOrder = -1;
} else {
$(this).addClass('asc selected');
$(this).removeClass('desc');
sortOrder = 1;
}
var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc
if (!this.asc) {
rows = rows.reverse()
}
for (var i = 0; i < rows.length; i++) {
table.append(rows[i])
}
})
}); //close of document ready
//Update Project Tracker list item Script
$(document).ready(function() {
jQuery(document).on("click", '#UpdateListItem', function() {
updateListItem();
}); //button closed
jQuery(document).on("click", '#UpdateClose', function() {
$("#updateForm").fadeOut();
}); //button closed
function updateListItem() {
//var listName = "ProjectTracker";
var url = _spPageContextInfo.webAbsoluteUrl;
var myID = $("#itemID").val();
var listName = "ProjectTracker";
var office = $("#uOffice").val();
var pTitle = $("#uProjectTitle").val();
var priority = $("#uPriority").val();
var startDate = $("#uStartDate").val();
var assignedTo = $("#uAssignedTo").val();
var status = $("#uStatus").val();
var requestor = $("#uRequestor").val();
var title = "New Updated Information";
var itemType = "SP.Data.Project_x0020_TrackerListItem";
console.log(office);
var item = {
"__metadata": {
"type": itemType
},
"Title": title,
"Office": office,
"ProjectTitle": pTitle,
"Priority": priority,
"StartDate": startDate,
"AssignedTo": assignedTo,
"Status": status,
"Requestor": requestor
};
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ProjectTracker')/items(" + myID + ")",
type: "POST",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
jQuery("#success").fadeIn();
}
function onError(error) {
alert(JSON.stringify(error));
}
} //Function close
});
Why is google not returning an object with a formatted address when using auto-complete and how can I get a formatted address?
When I log the variable from_place it returns an object like so:
but when I log to_place it returns an object with formatted_address:
I realise I'm using autocomplete on the first form and that's affecting it but how do i get to not affect or give me the formatted address?
// declare variables
var map, infoWindow, placeSearch, autocomplete;
// autocomplete form
var componentForm = {
locality: "short_name",
postal_code: "short_name"
};
// autocomplete form
// init google map API's
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 6
});
infoWindow = new google.maps.InfoWindow();
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
// console.log(pos)
infoWindow.setPosition(pos);
infoWindow.setContent("Location found.");
infoWindow.open(map);
map.setCenter(pos);
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
}
);
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
google.maps.event.addDomListener(window, "load", function() {
autocomplete = new google.maps.places.Autocomplete(
document.getElementById("from_places"),
{ types: ["geocode"] }
);
var to_places = new google.maps.places.Autocomplete(
document.getElementById("to_places")
);
google.maps.event.addListener(autocomplete, "place_changed", function() {
// var from_place needs to return an object with a formatted adress
var from_place = autocomplete.getPlace();
console.log(from_place);
var from_address = from_place.formatted_address;
$("#origin").val(from_address);
});
google.maps.event.addListener(to_places, "place_changed", function() {
var to_place = to_places.getPlace();
console.log(to_place);
var to_address = to_place.formatted_address;
$("#destination").val(to_address);
});
autocomplete.setComponentRestrictions({
country: ["uk"]
});
to_places.setComponentRestrictions({
country: ["uk"]
});
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(["address_component"]);
// When the user selects an address from the drop-down, populate the
// address fields in the form.
autocomplete.addListener("place_changed", fillInAddress);
});
// add all functions related to google in here
// collection to drop off
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 7,
center: { lat: 41.85, lng: -87.65 }
});
directionsRenderer.setMap(map);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsRenderer);
};
// One destination must be set at anyone time because
// 70 InvalidValueError: in property destination: must set one of location, placeId or query
document
.getElementById("googleAlgorithm2")
.addEventListener("click", onChangeHandler);
function calculateAndDisplayRoute(directionsService, directionsRenderer) {
directionsService.route(
{
origin: {
query: document.getElementById("from_places").value
},
destination: {
query: document.getElementById("to_places").value
},
travelMode: "DRIVING",
drivingOptions: {
departureTime: new Date(/* now, or future date */),
trafficModel: "pessimistic"
// departureTime: new Date(/* now, or future date */),
}
},
function(response, status) {
if (status === "OK") {
directionsRenderer.setDirections(response);
} else {
window.alert("Directions request failed due to " + status);
}
}
);
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(
browserHasGeolocation
? "Error: The Geolocation service failed"
: "Error Your browser does not support geolocation."
);
infoWindow.open(map);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = "";
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
If you want the formatted_address returned, you need to specify that field.
Instead of:
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(["address_component"]);
Do:
autocomplete.setFields(["address_component", "formatted_address"]);
You are only calling setFields on one of your autocomplete inputs. If you don't call it, you get (and pay for) all the fields in the PlaceResult
proof of concept fiddle
// This sample uses the Autocomplete widget to help the user select a
// place, then it retrieves the address components associated with that
// place, and then it populates the form fields with those details.
// This sample requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script
// src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), {
types: ['geocode']
});
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['address_component', 'formatted_address']);
// When the user selects an address from the drop-down, populate the
// address fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
document.getElementById('formatted_address').innerHTML = "formatted_address:<br>" + place.formatted_address;
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style><link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"><style>#locationField,
#controls {
position: relative;
width: 480px;
}
#autocomplete {
position: absolute;
top: 0px;
left: 0px;
width: 99%;
}
.label {
text-align: right;
font-weight: bold;
width: 100px;
color: #303030;
font-family: "Roboto";
}
#address {
border: 1px solid #000090;
background-color: #f0f9ff;
width: 480px;
padding-right: 2px;
}
#address td {
font-size: 10pt;
}
.field {
width: 99%;
}
.slimField {
width: 80px;
}
.wideField {
width: 200px;
}
#locationField {
height: 20px;
margin-bottom: 2px;
}
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text" />
</div>
<div id="formatted_address"></div>
<!-- Note: The address components in this sample are typical. You might need to adjust them for
the locations relevant to your app. For more information, see
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
-->
<table id="address">
<tr>
<td class="label">Street address</td>
<td class="slimField"><input class="field" id="street_number" disabled="true" /></td>
<td class="wideField" colspan="2"><input class="field" id="route" disabled="true" /></td>
</tr>
<tr>
<td class="label">City</td>
<td class="wideField" colspan="3"><input class="field" id="locality" disabled="true" /></td>
</tr>
<tr>
<td class="label">State</td>
<td class="slimField"><input class="field" id="administrative_area_level_1" disabled="true" /></td>
<td class="label">Zip code</td>
<td class="wideField"><input class="field" id="postal_code" disabled="true" /></td>
</tr>
<tr>
<td class="label">Country</td>
<td class="wideField" colspan="3"><input class="field" id="country" disabled="true" /></td>
</tr>
</table>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete" async defer></script>
I added a real-time stock widget to a client’s Jive site that is using an HTML widget. The code uses the Jive native jQuery library to pull JSONP data from Yahoo using their YQL API. This widget is written to work with only 1 stock symbol. If requested, I can modify it to pull in multiple symbols.
I keep getting an error for if (res.query.results). It says it is undefined. If anybody knows of a good stock HTML widget with just price and name of symbol: Please help. I am digging deep in Google.
Console output:
render-widget.jspa?size=1&frameID=262901&widgetType=7&containerID=1327&containerType=700&inFrame=1:173 Uncaught TypeError: Cannot read property 'results' of undefined
at Object.success (render-widget.jspa?size=1&frameID=262901&widgetType=7&containerID=1327&containerType=700&inFrame=1:173)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at x (jquery.min.js:4)
at HTMLScriptElement.b.onload.b.onreadystatechange (jquery.min.js:4)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
// This version has been tested to work in Jive 4.0.15 and 5.0. It should work in Jive 4.5 but has not been tested
// Add the stock symbol here
var yourStockSymbol = 'LIFE';
</script>
<div id="stock_miniQuote_head" class="ajaxtrigger"><span id="stockSymbol"></span> (common stock)</div>
<div id="stock_miniQuote">
<div id="stockIndicator"><p>Retrieving stock information...</p></div>
<div class="stock_divider">
<div id="stock_left">
<span class="stock_label">Price</span><br/>
<strong class="stock_strong">$<span id="stockAsk"></span></strong><br/>
</div>
<div id="stock_right">
<span class="stock_label">Change</span><br/>
<strong class="stock_strong"><span id="stockChange"></span></strong><br />
<strong class="stock_strong"><span id="stockChangePercent"></span></strong><br />
</div>
<div style="clear: both;"></div>
</div>
<div id="stock_body">
<div id="stock_body_content">
<span class="stock_label">Volume</span><br/>
<strong class="stock_strong"><span id="stockVolume"></span></strong>
<br /><br />
<span class="stock_label">Average Daily Volume</span><br/>
<strong class="stock_strong"><span id="stockAvgVolume"></span></strong>
<br /><br />
<span class="stock_label">52 Week Range</span><br/>
<strong class="stock_strong"><span id="stockRange"></span></strong>
</div>
<div style="clear: both;"></div>
</div>
</div>
<style>
#stockIndicator {
text-align:left;
padding: 10px;
margin: 5px;
color: red;
}
.ajaxtrigger:hover {
cursor: pointer;
cursor: hand;
}
#stock_miniQuote_head {
background-color:#464A55;
color:#FFFFFF;
font-size:14px;
font-weight:bold;
padding-bottom:10px;
padding-left:10px;
padding-right:10px;
padding-top:10px;
}
#stock_miniQuote {
border-bottom-color:#DDDDDD;
border-bottom-left-radius:5px 5px;
border-bottom-right-radius:5px 5px;
border-bottom-style:solid;
border-bottom-width:1px;
border-left-color:#DDDDDD;
border-left-style:solid;
border-left-width:1px;
border-right-color:#DDDDDD;
border-right-style:solid;
border-right-width:1px;
border-top-color:initial;
border-top-style:none;
border-top-width:initial;
list-style-type:none;
margin-bottom:10px;
padding-bottom:0;
padding-top:10px;
vertical-align:text-top;
height: 100%;
width: 99%;
}
.stock_divider {
border-bottom:1px solid #B2B0AD; padding-bottom:5px;
}
#stock_left {
float:left; width:35%; height:50px; border-right:1px solid #B2B0AD; padding:0 15px;
}
#stock_right {
float:right; width:*; padding:0 20px; vertical-align:text-top;
}
.stock_label {
font-size:14px;
}
.stock_strong {
font-size:17px;
}
#stock_body {
padding:10px 0 15px;
}
#stock_body_content {
float:left; width:170px; padding:0 15px;
}
</style>
<script type="text/javascript">
if ($('#jive-widgets-browser').css('display') == 'block') {
// Do Nothing as we are in edit mode
} else {
// Build the URL to Yahoo YQL services
var q = escape('select * from yahoo.finance.quotes where symbol in ("' + yourStockSymbol + '")');
var theURL = "https://query.yahooapis.com/v1/public/yql?q=" + q + "&format=json&diagnostics=false&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=?";
$(document).ready(function(){
// Load function on launch
$("#stockIndicator").show();
doAjax(theURL);
// Function for refreshing the stock by clicking on the title header
$('.ajaxtrigger').click(function(){
$("#stockIndicator").show();
doAjax(theURL);
return false;
});
// Function to add commas to numbers for volume
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
// Main function to make JSON request to Yahoo for stock information
function doAjax(url){
$.ajax({
url: url,
dataType: 'jsonp',
success: function(data){
var s = data.query.results;
if(s){
if(s.quote.Change > 0) {
// Change the change text to green
$('#stockChange').css({'color': 'green'});
$('#stockChangePercent').css({'color': 'green'});
} else {
// Change the change text to red
$('#stockChange').css({'color': 'red'});
$('#stockChangePercent').css({'color': 'red'});
}
// This is where we add the JSON values back into the HTML above
$('#stockSymbol').html(s.quote.symbol);
$('#stockAsk').html(s.quote.LastTradePriceOnly);
$('#stockChange').html(s.quote.Change);
$('#stockChangePercent').html(s.quote.ChangeinPercent);
$('#stockVolume').html(numberWithCommas(s.quote.Volume));
$('#stockAvgVolume').html(numberWithCommas(s.quote.AverageDailyVolume));
$('#stockRange').html(s.quote.YearRange);
$("#stockIndicator").hide();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
$("#stockIndicator").show();
$("#stockIndicator").html(errormsg);
}
}
});
}
}); //end ready function
} //end first else
</script>
The Yahoo Finance APi was turned off earlier this year, including accessing this information via YQL queries. You will need to find an alternate service and update our code accordingly.
There was another thread about this here, Yahoo Finance API changes (2017)