Reputation: 930
JSON newbie here. I am trying to do a lookup for a specific value from a JSON file. Basically, I have a search box where user can select a "name" (see jSON) from the existing list of "name"(s) from an auto-complete drop-down. The idea is to return the corresponding "url" value of the entered "name".
JSON (docs.json):
[
{ "tag": "Tutorial", "name": "Using Cloud", "url": "http://example.com/staff/doc/platform_training/index.html" },
{ "tag": "Tutorial", "name": "Help Tutorials", "url": "http://example.com/mason/staff/doc/tutorials/help/agent.html" },
{ "tag": "Tutorial", "name": "Big Stuff", "url": "http://example.com/mason/staff/doc/tutorials/orientation.html" }
]
jQuery:
$('.livesearch').keypress(function (e) {
if (e.which == 13) {
searchTerm = $("#search").val();
// return the "url" based on the "searchTerm", which is basically the "name" key in the JSON file
}
});
function readJSON(searchTerm) {
$.getJSON( "json/docs.json", function( data ) {
$.each( data, function( key, val ) {
//
});
});
}
HTML:
<input class="livesearch" type="text" placeholder="Enter your search terms here" id="search" />
Upvotes: 2
Views: 1277
Reputation: 104785
After you set your searchTerm
, call the readJSON(searchTerm)
function, then in your callback do:
var url = "";
for (var i = 0; i < data.length; i++) {
if (data[i].hasOwnProperty("name")) {
if (data[i].name == searchTerm) {
url = data[i].name;
break; //bye bye for loop
}
}
}
//do stuff
Upvotes: 1