I have Live Search JSON Data Using Ajax jQuery, and I would like to call more than one JSON file for the search.
At the start of the page, with the input empty, the results are not shown.
However, if you write and delete text again in the input, all results are displayed.
I would like to hide all the results again when the input is empty again.
Thank you in advance.
HTML Input:
<div class="container" style="width:900px;">
<div align="center">
<input type="text" name="search" id="search" placeholder="Search Employee Details" class="form-control" />
</div>
<ul class="list-group" id="result"></ul>
</div>
JavaScript:
<script>
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('1.json', function(data) {
$.each(data.entries, function(key, value){
if (value.title.search(expression) != -1 || value.author.search(expression) != -1)
{
$('#result').append('<li class="list-group-item link-class">'+value.title+' <span class="text-muted">'+value.author+'</span></li>');
}
});
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
</script>
2
Answers
Using
keypress
andkeydown
check the length before the text change. You can usekeyup
andchange
.It is better to use it with
keyup
:You can also use
change
:The change will be executed when you click somewhere else on the page.