I am trying to get data from JSON and present it with my 'Search' function, after I display the data I want to clear the result until the user will enter new word. Now it is displaying my all JSON file without clearing it.
The code looks like that:
<body>
<br>
<div id="searcharea">
<h2>Search Word</h2>
<input type="search" id="search"/>
</div>
<div id="update">
</div>
<script type="text/javascript" src='//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type="text/javascript">
$('#search').keyup(function() { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
$.getJSON('index.json', function(data){ //get the json file
var output = "<ul id='result'>";
$.each(data, function(key, val){
if(val.name.search(myExp) != -1){ //search for the data in the json file
output += '<li>';
output += '<h3>' +val.name+ '</h3>';
output += '<h3>' +val.song+ '</h3>';
output += '<h3>' +val.part+ '</h3>';
output += '</li>';
}
});//end each
output += "</ul>";
$('#update').html(output); //output result to the update div
});
});
</script>
</body>
The JSON file looks like that:
[
{
"name":"Word: 'asked' ",
"song":"Name of the song: 'Drive My Car' ",
"part":"Part: 1"
},
{
"name":"Word: 'a' ",
"song":"Name of the song: 'Drive My Car' ",
"part":"Part: 1, 2, 3"
}
]