Home > Software engineering >  Run search function on each keypress
Run search function on each keypress

Time:02-08

I have this function that when I click on submit or press Enter that uses the value in the input and scans for it in the child of each div, and if it finds one it hides all and shows only that div.

However I want to make this function run/scan with each keypress so that it continuously updates the list of results and not only when you submit.

I tried .on('keypress), keyup, keydown, keypress with no luck so far.

$('.search-form').on('submit',function(){return false;});
    $('.hidden-submit-button').on('click', function(e){
    var query = $.trim($(this).prevAll('.search-input').val()).toLowerCase();
    $('div.team_single-member .person-name').each(function(){
      var $this = $(this);
        if($this.text().toLowerCase().indexOf(query) === -1)
            $this.closest('div.team_single-member-wrap').hide();
        else $this.closest('div.team_single-member-wrap').show();
    });
});

CodePudding user response:

To do what you require you can change the event handler to listen for the input event on the .search-input directly.

Also note that you can use a case-insensitive version of the :contains selector to make your code more succinct:

jQuery.expr[':'].icontains = (a, i, m) => jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;

$('.search-form').on('submit', e => e.preventDefault());

$('.search-input').on('input', e => {
  var query = e.currentTarget.value.trim().toLowerCase();  
  $('div.team_single-member .person-name').hide().filter(`:icontains(${query})`).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<form >
  <input type="text"  />
</form>

<div >
  <p >Foo</p>
</div>  
<div >
  <p >Bar</p>
</div>  
<div >
  <p >Fizz</p>
</div>  
<div >
  <p >Buzz</p>
</div>  

  •  Tags:  
  • Related