I have an ajax search box that goes to the server on every key stroke and returns the result of the search. When the user types quickly, I want to search only on the last entry and not on every key stroke. Otherwise the individual results flash annoyingly and the whole process is slowed.
For example: if the user types "statue of liberty" quickly, I don't want to search on "sta", "stat", "statu" etc.
the basics of my jQuery code is:
$('#searchbox').keyup(function(){
if (this.value.length > 2) {
$.post("remote.php",{'partial':this.value},function(data){
$("#gen_results").html(data);
});
}
});
<input id="searchbox" />
<div id="gen_results"></div>
use setTimeout or jQuery's autocomplete plugin
var timer;
$('#searchbox').keyup(function(){
if (this.value.length > 2) {
if (timer){
clearTimeout(timer);
}
timer = setTimeout(function(){
$.post("remote.php",{'partial':this.value},function(data){
$("#gen_results").html(data);
});
}, 1000);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With