How can I order the results of several async JQuery queries? - javascript

I'm pulling in information from several web services to display on a web page. I'd like to be able to order the results, but keep the fetching dynamic. However, the way I've structured the code means that the elements get inserted into the DOM in the order that the requests complete, which is non-deterministic. How can I guarantee a specific order, but avoid inserting 'dud' elements if one of the results errors out instead of returning valid info?
// Get my apps from iTunes
var iTunesLinks = ["525393529", "645218452", "737479996"];
var iTunesSquareSize = 128;
$.each(iTunesLinks, function(index, value) {
var iTunesLink = "https://itunes.apple.com/lookup?id=" + value + "&callback=?";
$.getJSON(iTunesLink, function(data) {
var items = [];
items.push("<section id=\"myApps\"><table>");
var results = data.results;
$.each ( results, function( key, val ) {
var appName = val.trackName;
var iconURL = val.artworkUrl100;
var appURL = val.trackViewUrl;
items.push( "<td align=center width=" + iTunesSquareSize + " style=\"vertical-align:top\">" + divStart + "</div><a href=" + appURL + " target=_blank>" + appName + "</a></td>" );
});
items.push("</table></section>");
$( "<td/>", {
"class": "applist",
html: items.join( "" )
}).appendTo( document.getElementById("myApps") );
});
});

You can use collect all the promises into an array, pass that to $.when() and then when that is resolved, you will have all the data from all the async ajax calls in order like this:
// Get my apps from iTunes
var iTunesLinks = ["525393529", "645218452", "737479996"];
var iTunesSquareSize = 128;
var promises = [];
$.each(iTunesLinks, function(index, value) {
var iTunesLink = "https://itunes.apple.com/lookup?id=" + value + "&callback=?";
promises.push($.getJSON(iTunesLink));
});
$.when.apply($, promises).done(function(/* arg1Array, arg2Array, arg3Array, ... */) {
// now process all the results in order
var items, results;
for (var i = 0; i < arguments.length; i++) {
// arguments[i] is an array of [data, statusText, jqXHR]
results = arguments[i][0].results;
items = [];
items.push("<section id=\"myApps\"><table>");
$.each ( results, function( key, val ) {
var appName = val.trackName;
var iconURL = val.artworkUrl100;
var appURL = val.trackViewUrl;
items.push( "<td align=center width=" + iTunesSquareSize + " style=\"vertical-align:top\">" + divStart + "</div><a href=" + appURL + " target=_blank>" + appName + "</a></td>" );
});
items.push("</table></section>");
$( "<td/>", {
"class": "applist",
html: items.join( "" )
}).appendTo( document.getElementById("myApps") );
}
});

Related

Callback function not defined even though it has been defined right before calling in javascript

I am using for loop get all the data place in a div. I have following code in javascript so far:
<script type="text/javascript">
function callback(){
$.getScript("/frontend/vendor/jquery/jquery.min.js", function() {
$('input').on('change', function(){
var qty = $(this).attr('id');
var price = $('#'+qty+'_price').attr('value');
var subtotal = qty * price;
$('#'+qty+'_total').html('€ '+subtotal);
})
});
}
function checkout(callback){
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++){
var eventId = unique[n];
$.ajax({
"url":"/get_my_product/"+ eventId,
"type":"GET",
"dataType":"json",
"contentType":"application/json",
success:function(response){
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>"+party+"</a></h5></td><td class='product-col'><h5 class='product-title'><a>"+response.date+"</a></h5></td><td value='"+response.price+"' id='"+n+"_price'>€ "+response.price+"</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='"+n+"' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='"+n+"_total'>€ "+response.price+"</td></tr>";
$('#data').append(html);
}
})
}
callback && callback();
}
checkout();
</script>
When I am trying to call the function after the loop completion it does not work. What is wrong here?
Change
function checkout(callback){
to
function checkout() {
I think the argument callback to the function checkout "shadows" the previously defined callback function. Then, when you call the function checkout you are passing nothing to the function, and callback will be undefined.
Or, in the last line, pass the function as an argument:
checkout(callback);
Makes no sense to add another version of jQuery to add events. You are not passing the callback to the method so it is always going to be undefined. And you are not waiting for the Ajax calls to complete before calling the callback.
// No reason for loading the JQuery version here
function addMyEvents() {
$('input').on('change', function() {
var qty = $(this).attr('id');
var price = $('#' + qty + '_price').attr('value');
var subtotal = qty * price;
$('#' + qty + '_total').html('€ ' + subtotal);
})
}
function checkout(callback) {
// hold the ajax calls
const myAjaxCalls = []
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++) {
var eventId = unique[n];
// push the ajax calls to an array
myAjaxCalls.push($.ajax({
"url": "/get_my_product/" + eventId,
"type": "GET",
"dataType": "json",
"contentType": "application/json",
success: function(response) {
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>" + party + "</a></h5></td><td class='product-col'><h5 class='product-title'><a>" + response.date + "</a></h5></td><td value='" + response.price + "' id='" + n + "_price'>€ " + response.price + "</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='" + n + "' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='" + n + "_total'>€ " + response.price + "</td></tr>";
$('#data').append(html);
}
}))
}
// if we have a callback
if (callback) {
// wait for all the ajax calls to be done
$.when.apply($, myAjaxCalls).done(callback)
}
}
// pass the function to the method.
checkout(addMyEvents);
Now the best part is you do not even need to worry about the callback to bind events. You can just use event delegation and it would work. This way whenever an input is added to the page, it will be picked up.
$(document).on('change', 'input', function() {
var qty = $(this).attr('id');
var price = $('#' + qty + '_price').attr('value');
var subtotal = qty * price;
$('#' + qty + '_total').html('€ ' + subtotal);
})
function checkout() {
let eventDate = JSON.parse(localStorage.getItem("events"));
var unique = eventDate.filter(function(itm, i, eventDate) {
return i == eventDate.indexOf(itm);
});
let items = [];
for (var n = 0; n < unique.length; n++) {
var eventId = unique[n];
$.ajax({
"url": "/get_my_product/" + eventId,
"type": "GET",
"dataType": "json",
"contentType": "application/json",
success: function(response) {
let party = 'Party name';
let html = "<tr class='product-row'><td class='product-col'><h5 class='product-title'><a>" + party + "</a></h5></td><td class='product-col'><h5 class='product-title'><a>" + response.date + "</a></h5></td><td value='" + response.price + "' id='" + n + "_price'>€ " + response.price + "</td><td><div class='input-group'><input class='vertical-quantity form-control dataqty' id='" + n + "' type='number'><span class='input-group-btn-vertical'></span></div></td><td id='" + n + "_total'>€ " + response.price + "</td></tr>";
$('#data').append(html);
}
})
}
}
checkout();

How to use Angular.js to populate multiple select fields using AJAX calls to different endpoints

I apologize up front for the possible lack of clarity for this question, but I'm new to Angular.js and my knowledge of it is still slightly hazy. I have done the Angular.js tutorial and googled for answers, but I haven't found any.
I have multiple select/option html elements, not inside a form element, and I'm populating them using AJAX. Each form field is populated by values from a different SharePoint list. I'm wondering if there is a way to implement this using Angular.js?
I would like to consider building this using Angular because I like some of it features such as data-binding, routing, and organizing code by components. But I can't quite grasp how I could implement it in this situation while coding using the DRY principle.
Currently, I have a single AJAX.js file and I have a Javascript file that contains an array of the different endpoints I need to connect to along with specific query parameters. When my page loads, I loop through the arrays and for each element, I call the GET method and pass it the end-point details.
The code then goes on to find the corresponding select element on the page and appends the option element returned by the ajax call.
I'm new to Angular, but from what I understand, I could create a custom component for each select element. I would place the component on the page and all the select and options that are associated with that component would appear there. The examples I've seen demonstrated, associate the ajax call with the code for the component. I'm thinking that I could use a service and have each component dependent on that service and the component would pass it's specific query details to the service's ajax call.
My current code - Program flow: main -> data retrieval -> object creation | main -> form build.
Called from index.html - creates the multiple query strings that are passed to ajax calls - ajax calls are once for each query string - the very last function in the file is a call to another function to build the form elements.
var snbApp = window.snbApp || {};
snbApp.main = (function () {
var main = {};
main.loadCount = 0;
main.init = function () {
function buildSelectOptions(){
//***
//Build select options from multiple SharePoint lists
//***
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
for(var i = 0; i < listsArray.length; i++){
var listItem = listsArray[i];
var qryStrng = listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
var listDetails = {
listName: listItem.list,
listObj: listItem,
url: "http://myEnv/_vti_bin/listdata.svc/" + listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
};
var clientContext = new SP.ClientContext.get_current();
clientContext.executeQueryAsync(snbApp.dataretriever.letsBuild(listDetails), _onQueryFailed);
}
//***
//Build select option from other API endpoint
//***
var listDetails = {
listName:"SNB_SecondaryActivityCodes",
url: "http://myEnv/requests/odata/v1/Sites?$filter=(IsMajor eq true or IsMinor eq true) and IsActive eq true and IsPending eq false and CodePc ne null and IsSpecialPurpose eq false&$orderby=CodePc"
};
snbApp.dataretriever.letsBuild(listDetails);
}
buildSelectOptions();
//***
//Add delay to populate fields to ensure all data retrieved from AJAX calls
//***
var myObj = setTimeout(delayFieldPopulate,5000);
function delayFieldPopulate(){
var optObj = snbApp.optionsobj.getAllOptions();
var osType = $("input[name=os_platform]:checked").val();
snbApp.formmanager.buildForm(osType, optObj);
}
};
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return main
})();
AJAX calls here - called from main/previous file:
var snbApp = window.snbApp || {};
snbApp.dataretriever = (function () {
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
function getListData(listItem) {
var eventType = event.type;
var baseURL = listItem.url;
$.ajax({
url: baseURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
})
.done(function(results){
snbApp.objectbuilderutility.buildObjectFields(results, listItem);
})
.fail(function(xhr, status, errorThrown){
//console.log("Error:" + errorThrown + ": " + myListName);
});
}
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return{
letsBuild:function(item) {
getListData(item);
}
};
})();
Builds a item name object - called from recursive AJAX calls / previous file
var snbApp = window.snbApp || {};
snbApp.objectbuilderutility = (function () {
function formatItemCode(itemCode, eventType){
if(eventType !== 'change'){ //for load event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(0,3);
}
}else{ //for change event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(3);
}
}
}
return{
buildObjectFields: function(returnedObj, listItem){ //results:returnedObj, prevItem:listItem
//***
//For SharePoint list data
//***
if (listItem.listName !== "SNB_SecondaryActivityCodes") {
var theList = listItem.listName;
var firstQueryParam = listItem.listObj.codeDigits;
var secondQueryParam = listItem.listObj.codeDescription;
var returnedItems = returnedObj.d.results;
var bigStringOptions = "";
//regex to search for SecondaryFunctionCodes in list names
var pattern = /SecondaryFunctionCodes/;
var isSecFunction = pattern.test(theList);
if(isSecFunction){
bigStringOptions = "<option value='0' selected>Not Applicable</option>";
}else{
bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
}
$.each(returnedItems, function (index, item) {
var first = "";
var second = "";
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key != "__metadata") {
if (key == firstQueryParam) {
first = item[key];
}
if (key == secondQueryParam) {
second = item[key];
}
}
}
}
bigStringOptions += "<option value=" + first + " data-code=" + first + ">" + second + "</option>";
});
var str = theList.toLowerCase();
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
//***
//For other API
//***
} else {
var theList = listItem.listName;
var bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
var returnedItems = returnedObj.value;
for(var i = 0; i < returnedItems.length; i++){
var item = returnedItems[i];
//***
//change event type means the user selected a field
//***
if(listItem.eventType === "change"){
var siteCodeChange = item.SiteCodePc;
if (typeof siteCodeChange === "string" & siteCodeChange != "null") {
siteCodeChange = siteCodeChange < 6 ? siteCodeChange : siteCodeChange.slice(3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeChange + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeChange + ") " + item.Name + "</option>";
snbApp.formmanager.buildSelectSiteLocations(bigStringOptions);
//***
//load event which means this happens when the page is loaded
//***
}else{
var siteCodeLoad = item.SiteCodePc;
if (typeof siteCodeLoad === "string" & siteCodeLoad != "null") {
var siteCodeLoad = siteCodeLoad.length < 4 ? siteCodeLoad : siteCodeLoad.slice(0, 3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeLoad + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeLoad + ") " + item.Name + "</option>";
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
}
}
}
}
};
})();
Form management - called from previous file, gets all select elements on page and appends items from the object in previous file to each select element.
var snbApp = window.snbApp || {};
//Direct interface to the form on the page
snbApp.formmanager = (function(){
var form = {};
form.content_holder = document.getElementById("content_holder");
form.sec_act_codes = document.getElementById("snb_secondary_activity_codes");
form.prim_func_codes = document.getElementById("snb_primary_function_codes");
form.sec_func_codes = document.getElementById("snb_secondary_function_codes");
form.sec_func_nums = document.getElementById("snb_secondary_function_numbers");
form.host_options = document.getElementById("snb_host_options");
form.site_locs_div = document.getElementById("site_locations_div");
form.site_locs = document.getElementById("snb_site_locations");
form.dc_or_off_prem_div = document.getElementById("dc_or_off_premise_div");
form.dc_off_prem_codes = document.getElementById("snb_dc_offpremise_codes");
var snb_secondary_activity_codes = "";
var snb_primary_function_codes = "";
var snb_secondary_function_codes = "";
var snb_secondary_function_numbers = "";
var snb_host_options = "";
var snb_site_locations = "";
var snb_dc_op = "";
//builds the server location hosting options selection
function buildLocationTypeSelector() {
var locationOptionsString = "<option value='0' disabled selected>Select Option</option>";
for (var i = 0; i < locationOptions.length; i++) {
var location = locationOptions[i];
locationOptionsString += "<option value=" + location.hostLocale + " data-code=" + location.code + ">" + location.hostLocale + "</option>";
}
$("#snb_host_options").append(locationOptionsString);
}
function buildSiteLocations(bigString){
if(bigString === undefined){
var siteLocs = document.getElementById("snb_site_locations");
var newOption = document.createElement("option");
newOption.setAttribute("value", 0);
newOption.setAttribute("disabled","disabled");
newOption.setAttribute("checked","checked");
var newText = document.createTextNode("Select Option");
newOption.appendChild(newText);
siteLocs.appendChild(newOption);
} else{
var siteLocs = document.getElementById("snb_site_locations");
siteLocs.innerHTML = bigString;
}
}
return {
form:form,
buildSelectSiteLocations: function(bigString){
buildSiteLocations(bigString);
},
buildForm: function (osType, optObj) {
buildLocationTypeSelector();
buildSecondaryFunctionNumberSelector();
buildSiteLocations();
if(osType === 'windows'){
$("#snb_secondary_activity_codes").append(optObj.windows.secondary_activity);
$("#snb_primary_function_codes").append(optObj.windows.primary_function);
$("#snb_secondary_function_codes").append(optObj.windows.secondary_function);
$("#snb_site_locations").append(optObj.windows.site_location);
$("#snb_dc_offpremise_codes").append(optObj.windows.dc_offpremise);
}else{
$("#snb_secondary_activity_codes").append(optObj.unix.secondary_activity);
$("#snb_primary_function_codes").append(optObj.unix.primary_function);
$("#snb_secondary_function_codes").append(optObj.unix.secondary_function);
$("#snb_site_locations").append(optObj.unix.site_location);
$("#snb_dc_offpremise_codes").append(optObj.unix.dc_offpremise);
}
}
};
})();
Thanks in advance.

min & max of values in looped-thru JSON data (no jQuery)

In the following:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
} // processResponse
if (weighInData[obj].user === selUser) { ... returns the following (using example Ron):
Object { user="Ron", date="2014-08-01", weight="192"}
Object { user="Ron", date="2014-08-02", weight="195"}
Object { user="Ron", date="2014-08-03", weight="198"} ... etc.
... so my problem presently is where this belongs:
var peakWeight = Math.max.apply(Math, weights);
console.log("peakWeight: " + peakWeight);
Since I'm only after the weight values for the matching user, I assumed it would have to run within the 'if (weighInData[obj].user === selUser) { ... ', but this (and numerous other attempts in and out of the loop, including a for loop within the selUser) fail to achieve the desired results. In fact, even when the math function wasn't running on each value in 'weights', (i.e., outside the loop) and only ran outside the loop, the result was an incorrect value.
Any insight is greatly appreciated,
svs
Here's a very simple example you can probably adjust to fit your purpose:
// create this array outside of for loop so it already exists
var arr = [];
// test data
var a = { user:"Ron", date:"2014-08-01", weight:"192"};
var b = { user:"Ron", date:"2014-08-02", weight:"195"};
var c = { user:"Ron", date:"2014-08-03", weight:"198"};
// within for loop, you should only need to push once (per loop)
arr.push( a.weight );
arr.push( b.weight );
arr.push( c.weight );
// after the loop ends, display loop, get max and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
http://jsfiddle.net/biz79/sb7zayze/
If i were to edit your code, something like this might work:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
// ADDED: create array
var arr = [];
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
// ADDED: add to array
arr.push(weights);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
// ADDED: after the loop ends, display loop, get max/min and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
} // processResponse

Hiding <p> field in javascript

Here's my code for gathering titles/posts from reddit's api:
$.getJSON("http://www.reddit.com/search.json?q=" + query + "&sort=" + val + "&t=" + time, function (data) {
var i = 0
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
i++
});
});
Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?
Could you try something like the below?
showhide = $("<a class='hider'>Show/Hide</a>");
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
}
Alternatively:
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var showhide = $("<a class='hider" + i + "'>Show/Hide</a>");
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
});
i++
});

search with an array associate with javascript?

I want to do a search by name and surname with an array javascript, and the results in a div. for example: I write Ali in input, an it shoul show me Alison and Alibaba.
this is my code, but it's giving errors; are there other ways to do it?:
<input type='text' id='filter' placeholder='search'>
<div id='output' style='margin-top:50px '></div>
my array
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#output');
$('#filter').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
console.log( item[0].toLowerCase().indexOf(val));
if ( item[0].toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item[0] + ' ' + item[1] + '</li>');
}
});
$result.html( $fragment.children() );
});
http://jsfiddle.net/henrykend/ChpgZ/4/
The main problem with your code is that you're trying to reference fields in the object by ordinal position rather than name. There is nothing automagic in JavaScript which will read item.Name (or item["Name"]) from item[0].
There is also no need to build up a "false element" (in your case $fragment) and then append its children to the output area - you may as well do this in one go (remembering to .empty() it between calls).
Your corrected code:
var $result = $('#result');
$('#output').on('keyup', function () {
$result.empty();
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$result.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
});
And a live example: http://jsfiddle.net/ChpgZ/6/
You had couple of problems in your code.
Names of the elements we're wrongly placed (which you've fixed with the edit)
In the .each, you've used item[0] instead of item.Name (also surname)
See the following code
var arrayD =[
{"Name":"Alison","Surname":"Kenn","Mobile":529129293},
{"Name":"Ashton","Surname":"Jhojan","Mobile":529129293},
{"Name":"Bith","Surname":"Klint","Mobile":129129293},
{"Name":"Ana","Surname":"Clow","Mobile":229129293},
{"Name":"Geoge","Surname":"Rich","Mobile":329129293},
{"Name":"kenneth","Surname":"Cooler","Mobile":329129}
]
var $result = $('#result');
$('#output').on('keyup', function () {
var $fragment = $('<div />');
var val = this.value.toLowerCase();
$.each(arrayD, function (i, item) {console.log( item.Name.toLowerCase().indexOf(val) );
if ( item.Name.toLowerCase().indexOf(val) == 0 ) {
$fragment.append('<li>' + item.Name + ' ' + item.Surname + '</li>');
}
});
$result.html( $fragment.children() );
});

Categories