Jeff Walden Jeff Walden - 6 months ago 26
Ajax Question

Which event to use for search input

I have a search field which collects a query and performs a search with an AJAX request. I'm having trouble finding the perfect javascript event to use to execute the search.

oninput
Using oninput, the AJAX request is fired multiple times, once for each character in the input field. So searching for '123' will perform three AJAX requests:


  1. '1'

  2. '12'

  3. '123'



onchange
Using onchange is more efficient in that it only fires a single AJAX request, but it forces the user to change focus from the search field in order to fire.

Is there a javascript event that I can use to have the best of both worlds? I'm using a timeout delay of 1.5 seconds on search to give the user enough time to enter the search query. Ideally, I'd like to use a JS event like oninput that fires without requiring the field loses focus, but only fires once for the entire value rather than once for each character in the input field.

Maybe the answer is to use the onchange event and automatically lose focus after 1.5 seconds? This just seems hacky and also introduces a usability issue in that if the user wants to change the search query they would need to set focus on the search field again.

Answer

This is how you could do it, debouncing input event:

$('input[type=search]').on('input', function(){
   clearTimeout(this.delay);
   this.delay = setTimeout(function(){
      console.log(this.value);
      /* call ajax request here */
   }.bind(this), 800);
});

And for better UIX, you should bind search event too:

$('input[type=search]').on('search', function(){
   if(this.value){
     /* call ajax request here */
   }
});

See -DEMO-