Reputation: 11
I created the script to get the data from external JSON file and append to #test element:
$(document).ready(function(){
$.getJSON('/path_to_json_file',function(json){
$.each(json, function(i,data){
$("#test").append('<li class="col-xs-4 col-md-3 ' + data.status + '" data-id="' + data.id + '"><div class="area view"><div class="game-label ' + data.title + '"><div class="news">News</div></div><div class="image ' + data.url_title + '"></div><div class="mask"><a href="" class="btn">BTN1</a><a href="" class="btn">BTN2</a><a href="#' + data.url_title + '" class="btn ' + data.info_visible + '"><span class="glyphicon glyphicon-info-sign"></span></a><a class="btn btn-star for-members"><span class="glyphicon"></span></a></div></div><div class="game-name sr-only"><a href="#">' + data.title + '</a></div></li>');
});
});
});
Everything work well. But also I'd like to make an option to search JSON data and show the results on page. While typing the name of the entry (jsondata6) in input all entries not match the search sentence should gone so the user can see the correct items only.
SEARCH INPUT
<input type="search" name="search" id="search" value="" />
JSON FILE
{"jsondata1":"jsondata1",
"jsondata2":"jsondata2",
"jsondata3":"jsondata3",
"jsondata4":"jsondata4",
"jsondata5":"jsondata5",
"jsondata6":"jsondata6"
}
MARKUP FROM JSON
<ul id="test">
<li class="col-xs-4 col-md-3 jsondata1" data-id="jsondata2">
<div class="area view">
<div class="game-label jsondata3">
<div class="news">News</div>
</div>
<div class="image jsondata4"></div>
<div class="mask">
<a href="" class="btn btn-play js-run-game"></a>
<a href="" class="btn btn-demo js-run-demo"></a>
<a href="#" class="btn btn-info jsondata5"><span class="glyphicon glyphicon-info-sign"></span></a>
<a class="btn btn-star"><span class="glyphicon"></span></a>
</div>
</div>
<div class="game-name sr-only"><a href="#">jsondata6</a></div>
I'm trying to modify the script above but no luck so far. Any help?
Thanks!
Upvotes: 1
Views: 2000
Reputation: 1985
i would probably push the fetched json data into an array, like
var some_global_array=[]
$.each(json, function(i,data){
some_global_array.push(data);
}
then created the elements from the filled array. it will be much easier to perform search then. the container li
would then have data-my-array-id
(or a class, what you like better) integer attribute
each search would then iterate over the some_global_array
(like for(var i=0;i<some_global_array.length;i++){...
and find which indeces should be hidden/shown by your data-search logic. then if you find that the index should be shown, just do hide the element with data-my-array-id
of an element that does not fit search criteria/show all the other ones
Upvotes: 1