/* JSON search v1.0 */
/* initiate variables
* @jsonData used in function callback
* @regex used in function useParsedData & defined onkeyup of search field
* @searchField = the id of your search input field; the where people type to search for something
*/
var jsonData,
regex,
searchField = document.querySelector("#search");
/*
* FUNCTION Callback
* function to get JSON data
* param @json = your JSON formatted data; the complete data set you want to search within
*/
function callback(json) {
jsonData = json.page; // change "photo" to the 1st level of your json data -> see documentation for more examples
useParsedData(json.page);
}
/**
* FUNCTION useParsedData
* parse JSON data; use data to create unordered list; insert search results in DOM
* param @data = 1st level of your JSON formatted data
*/
function useParsedData(data) {
var output = "
";
var test = "#df_book_page_number";
// cycle through each item in JSON data
data.forEach(function(key, index, val) {
console.log(data[index]['@attributes'].id);
// name, role & category are the second level items in json data -> change these to match your JSON structure -> see documentation for more examples
if ((data[index]['@attributes'].id.search(regex) != -1) || (key.keywords.search(regex) != -1)) {
output += "
"; // substitute with whatever information you want to extract from your JSON data
output += "
";
}
});
output += '';
output += '
';
document.querySelector("#update").innerHTML = output; //insert search results in element with id="update"
}
// when someone types something into your search field, look for that keyword/phrase in your JSON data set
searchField.addEventListener("keyup", function() {
var searchInput = searchField.value;
regex = new RegExp(searchInput, "i"); // case insensitive! see http://www.w3schools.com/jsref/jsref_obj_regexp.asp for more info on regex
useParsedData(jsonData);
});
searchField.focus(); // put focus on search input field
// create script with JSON data and append it to your HTML document head
var script = document.createElement('script');
script.setAttribute("type", "text/javascript")
script.setAttribute("src", "js/search.php");
document.getElementsByTagName("head")[0].appendChild(script);