Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - Live search ajax calls as user types but with small delay?

Tags:

jquery

Due to environment I would like to constrain this to something small and concise rather than a plugin, unless it's an extension that can be put inline aside other jquery code.

I have this code:

$("#txtSearch").live('keyup', function () {
    LoadList(1)     
});

I'd like to add a delay such that if a user must wait (as in stop typing) 0.5 seconds before a call is executed.

So basically if letters are typed with less than X time between consecutive keystrokes no ajax call occurs.

Is there a tiny concise way to do this with Jquery?

like image 515
Joshua Enfield Avatar asked Jun 20 '11 21:06

Joshua Enfield


2 Answers

Set a timeout and clear it on every keystroke before applying a new one:

var timeout;
$("body").on('keyup', '#txtSearch', function () {
    window.clearTimeout(timeout);
    timeout = window.setTimeout(function(){
       LoadList(1); 
    },500);

});

example: http://jsfiddle.net/niklasvh/KgRjJ/

like image 126
Niklas Avatar answered Sep 25 '22 12:09

Niklas


$("#txtSearch").live('keyup', function () {
    var value=$("#txtSearch").val();
    setTimeout(function(){
          if ($("#txtSearch").val() == value)
          {
                 LoadList(1)      
          }
    },500);
});
like image 35
genesis Avatar answered Sep 25 '22 12:09

genesis