skip to Main Content

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


  1. $('#search').keypress(function() { 
    if($(this).val().length > 1) { 
    // Continue work 
    } else { 
    $('#result').html('') 
    }
    
    Login or Signup to reply.
  2. Using keypress and keydown check the length before the text change. You can use keyup and change.

    It is better to use it with keyup:

    $('#txt1').keyup(function() {
        if (!$(this).val().length) $('#result').html('');
    });
    

    You can also use change:

    $('#txt1').change(function() { 
        if (!$(this).val().length) $('#result').html('');
    });
    

    The change will be executed when you click somewhere else on the page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search