search with an array associate with javascript? - 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() );
});

Related

jQuery .each get index of items

The array fetched has a key and value for each item but I want to get a simple index for each value ie 0, 1, 2, 3, 4 etc which currently is not what the key gives (and nor do I want it to). Using index also does not seem to work.
$.getJSON( "filepath/current.json", function(data) {
var items = [];
$.each( data, function(key,val) {
items.push( "<p id='" + key + "'>" + val + "</p>" );
});
});
For objects jQuery each doesn't support for an index parameter. But you can create an index for your own without any problems. ;)
var data = {
one: "ONE",
two: "TWO",
three: "THREE"
},
items = [];
//Use a simple counter ;)
(function() {
var i = 0;
$.each(data, function(key, val) {
items.push("<p id='" + i + "'>" + val + "</p>");
i++;
});
})();
console.log(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this:
var data = ["aa", "bb", "cc"];
var items = data.map((val, index) => "<p id='" + index + "'>" + val + "</p>");
console.log(items);
And it even cleaner with ECMAScrpt6 template litteral:
var data = ["aa", "bb", "cc"];
var items = data.map((val, index) => `<p id='${index}'>${val}</p>`);
console.log(items);
The key property is literally the index. If the key isn't a numeric index then your data is not an array but an object.
Your choices are:
a) rethink and redesign the solution. What are you going to use 0, 1, 2 etc for? Can it be replaced?
b) introduce a variable outside the each scope and manually increment it inside the scope. If you need to access the val later using the numeral index, you should map that data object to an array of objects containing only key and val properties.
$.getJSON( "filepath/current.json", function(data) {
var items = [];
for(key in data) {
var insert_key=parseInt(key)||0;
items.push( "<p id='" + insert_key + "'>" + data[key] + "</p>" );
}
});

How can i prevent duplicate entry in java script while appending data into #div

PFB java script code..
the thing is im getting alert for duplicate entry. how can avoid the repeated data?
Var activityconunt =0;
if (activityconunt !== data.iRoundId) {
alert("duplicate");
$("#selectRound_Type").append("<option name='round' id=" + data.iRoundId + ">" + data.strRoundName + "</option>");
}
my output
Solution one:
Take your data and build a clean array before. Using http://api.jquery.com/jquery.inarray/
Solution two:
Check your existing options for containing values
if($("option:contains('" + data.strRoundName + "')").length == 0)
$("#selectRound_Type").append("<option name='round' id=" + data.iRoundId + ">" + data.strRoundName + "</option>");
this should do it as well and is a shorter code
also see Fiddle
Use an array to store the data and check the new value with it:
$(function () {
var items = [];
var $select = $('select');
var $input = $('input');
var $button = $('button');
// fetch current data
$select.find('option').each(function () {
items.push($(this).text());
});
$button.on('click', function () {
var value = $input.val();
var exists = ($.inArray(value, items) != -1);
if (! exists) {
items.push(value);
$('<option></option').text(value).prependTo($select);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<button>Add</button>
<br />
<select style="width: 300px;">
<option>Hello</option>
</select>
Solution for preventing duplicate values and undefined value in the list
if ($("option:contains('" + data.strRoundName + "')").length == 0
&& data.strRoundName != null
&& typeof data.strRoundName != "undefined")
$("#selectRound_Type").append("<option name='round' id="
+ data.iRoundId + ">"
+ data.strRoundName + "</option>");

Loop through jquery data() object to get keys and values

I have a data() object containing some json.
Is there a way I can loop through the object and grab each parts key and value?
This is what I have so far:
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
figures = data.figures;
$.each(figures, function(index, figure) {
$('#figureList').append('<li> index = ' + data.figures.figure + '</li>');
});
});
$('#figureList').listview('refresh');
}
The json looks like this:
{"figures":{"value":"150000","completion":"10.00","coal":"32.40","local":"144.00","bacs":"35.00","landRegistry":"200.00","solFee":"395.00","vatOnSolFees":79,"stampDuty":1500,"total":2395.4}}
Apologies if its simple, I'm new to jQuery and couldn't find anything on SO that helped.
You can get the key and value like this
$.each(data.figures, function(key, val) {
console.log('Key: ' + key + ' Val: ' + val)
});​
So change your code to
$('#figureList').append('<li>'+ index + ' = ' + figure + '</li>');
Demo: http://jsfiddle.net/joycse06/ERAgu/
The parameters index and figure contains the parameter name and value. I think that you want to concatenate the parameters into the string:
$('#figureList').append('<li>' + index + ' = ' + figure + '</li>');
An alternative is to create the list item element and set the text of it, that would also work if the text contains any characters that need encoding:
$('#figureList').append($('<li/>').text(index + ' = ' + figure));
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
$.each(data['figures'], function(index, val) {
here grab "val" is key
$.each(data['figures'][index], function(col, valc) {
here grab "col" is value
}
}
}
bye

jQuery JSON looping through nested objects

I currently have this:
$.getJSON('test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
test.json looks like this:
{"key1":{"key11":"value11","key12":"value12"},"key2":"value2","key3":"value3"}
I'm getting:
[object Object]
value2
value3
How can I change it so it will loop through all the nested items regardless of how many nested values I have?
So for the above example I will get
value1
value11
value12
value2
value3
You can make a recursive loop function, but you'd have a problem: when a property is an object, there is no text to display because there is no string. So, you'll end up with:
- - value11
- value12
- value2
- value3
because while value2 is the string to display for item #2, it is an object that's displayed for item #1.
Anyway, this is what I made up: http://jsfiddle.net/uXww2/.
// obj is the object to loop, ul is the ul to append lis to
function loop(obj, ul) {
$.each(obj, function(key, val) {
if(val && typeof val === "object") { // object, call recursively
var ul2 = $("<ul>").appendTo(
$("<li>").appendTo(ul)
);
loop(val, ul2);
} else {
$("<li>", {
id: key
}).text(val).appendTo(ul);
}
});
}
$.getJSON('test.json', function(data) {
var ul = $("<ul>");
loop(data, ul);
ul.addClass("my-new-list").appendTo('body');
});
so, what you want is a treeview looping through a json object
you can use this code i made myself recursively, test it ;)
var treestring = "";
var myid = "arv";
var json_object = {your json};
var Tree = function (data) {
this.data = data;
};
//1st step
Tree.renderTree(json_object, myid);
//2st step , this is a function
Tree.renderTree= function (json_object, myid) {
$.each(json_object, function (key, val) {
var m = new Tree(val);
m.render(myid);
});
}
//3st step, this a function too
Tree.prototype.render = function (myid) {
treestring = "<li class='category'> " + this.data.Name;
//Check if has another arrays inside the current
if (this.data.SubFolders) {
treestring += "<ul id=" + this.data.ID + "</ul>";
$("#" + myid).append(treestring);
myid = this.data.ID;
Tree.renderTree(this.data.Sub_Fodlers, myid);
}
else {
treestring += "</li>";
$("#" + myid).append(treestring);
}
};
//HTML
<div id="tree">
<ul id="arv"></ul>
</div>
//this.data.{something} ate the fields defined in your json object
enjoy ;)

Another jQuery autocomplete issue

So, i have read at least 20-30 auto complete problems here on so and i cannot find any solutions. For some odd reason i keep getting value = undefined. Here is my code.
//Cycles through each input and turns it into a person searcher.
$.each(settings.input, function() {
var input = $(this);
input.autocomplete({
delay: 70,
minLength: 2,
source: function(req, add) {
var val = input.val();
$.post(VUI.SITE_URL + "scripts/autocomplete/_AutoComplete.php", {q: val, display_count: settings.displayCount, action: "user"}, function(data) {
data = eval("(" + data + ")");
if (data.length > 0) {
var results = new Array(data.length);
$.each(data, function(key, value) {
results[key] = {desc: value, value: value.firstname + " " + value.lastname};
});
add(results);
} else {
add(["No results..."]);
}
});
},
select: function(event, ui) {
alert(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
}
}) // end auto complete.
.data("autocomplete")._renderItem = function($ul, item) {
var $li = $("<li></li>"),
$inner = $("<div class='st-display side-content clearfix'style='padding-top:6px'></div>"),
$a = $("<a></a>"),
$img = $("<div class='image fl'></div>").html(ST.Image.getImage({
uid: item.desc.uid,
type: ST.ST_IMAGE_TYPE_THUMBNAIL_SMALL
})),
$content = $("<div class='content fl'></div>").html(
item.desc.firstname + " " + item.desc.lastname + "<br/>" +
"<span class='color:#979797;font-weight:bold'>" + item.desc.city + ", " + item.desc.state + "</span>"
);
$inner.append($img).append($content);
$a.append($inner);
$li.append($a);
$ul.append($li);
return $ul;
} // end _renderItem */
I tried to make it so that its very straight forward. But it wont work! (its facebook like auto complete). The auto complete displays properly (item does not equal undefined at that point), but when i highlight it, item becomes undefined so item.value (line 6347 of jquery.ui.1.8.13) throws exception!
Anyone see problems?
Here is something interesting... When i do not use data("autocomplete")._renderItem (for custom completion) the selecting works! ... So why does overriding the custom rendering cause issues? I am even returning the UL.
The only thing in your code that's different from a working version I've got of something very similar is that I initialise $li with:
var $li = $( '<li></li>' ).data('item.autocomplete', item);
That attaches the data to the list item which I think the autocomplete plugin uses to get the value at selection time.
Hope it helps

Categories