I wrote this script to my live search:
$(document).ready(function(){
$('input#search').keypress(function(){
$('ul#pacientes_hint').html("");
var texto = $('input#search').val();
if(texto.length > 2){
$('ul#pacientes_hint').html("");
$.post("../index.php/buscar/busca2", { "texto" : texto},
function(data){
$('ul#pacientes_hint').html("");
var html_final = "";
$.each(data, function(key, value) {
html_final = html_final + value.msg;
});
$('ul#pacientes_hint').html(html_final);
}, "json");
}else{
$('ul#pacientes_hint').html("");
}
});
});
It’s working ok and all but when I type too fast it spams querys, how can I make it so only one script execution (the last keypress) runs at a time?
You may be best off using Throttle/Debounce by Ben Alman:
http://benalman.com/projects/jquery-throttle-debounce-plugin/