Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  177] [ 7]  / answers: 1 / hits: 23920  / 15 Years ago, thu, july 23, 2009, 12:00:00

I've got a search input which sends data from an input to a php file as I type. The php file does a search on my database and shows up a list of search options. You know, the ajax style live searching.



My problem is, if you type something really fast, it might just conduct a search off of the first 1 or 2 letters even though another 10 have been typed. This causes a few problems.



My jQuery looks a bit like this:



$(document).ready(function(){
$('#searchMe').keyup(function(){
lookup(this.value);
});
});


and



function lookup(searchinput) {

if(searchinput.length == 0) {
// Hide the suggestion box.
$(#suggestions).hide();
} else {

$('#loading').fadeIn();

$.post(/RPCsearch.php, {queryString: +searchinput+}, function(data){
if(data.length > 0) {
$(#suggestions).html(data).show();
$('#loading').fadeOut();
}
});
}
} // lookup


So I'm just curious, how can I make it so that my script waits until I've finished typing before running the function? My logic says something like if a key hasn't been pressed for 200 micro seconds, run the function, otherwise hold up a bit.



How is this done?


More From » jquery

 Answers
51

Easy, using setTimeout. Of course you only want one timer going at once, so it's important to use clearTimeout at the beginning of the function...



$(function() {
var timer;
$(#searchMe).keyup(function() {
clearTimeout(timer);
var ms = 200; // milliseconds
var val = this.value;
timer = setTimeout(function() {
lookup(val);
}, ms);
});
});

[#99071] Sunday, July 19, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;