I'm trying to implement a search box using php and jquery (the seach results are coming from a database). What I want to do is that as the user type into the search box, a query is made to find the data that contains the keyword the user entered into the search box. The problem I'm having is that I have something like this:
$("#my_search_box").keyup(function(){
retrieve_results($(this).val());
});
The problem with doing this is that, the function retrieve_results() is called every time the user is done typing (of course, cause that's what the keyup is there for). Therefore, this can get very slow because if the user type a word that has like 10 characters, the retrieve_results() function gets called 10 times in a row. Also, I should mention that inside my retrieve_results() function, I'm doing an Ajax request using jQuery $.ajax to get the results. So my question is the following:
How do I make it so that my function retrieve_results() doesn't get executed everytime the user stops typing (every time the key is up). I want to keep that functionality though, I don't want the user to click on a "Search" button or something. I just would like my retrieve_results() function to get called only once when the user is done entering all the keywords (not everytime the user enters a letter or something)
Thank you
Ideally, you only want the search to fire for the very last character the user types. The best way to do this is to give him enough time to continually type, and if he pauses (even to think), run the search.
Using setTimeout
by itself won't work because even that would fire multiple times. You have to clear the timeout by using clearTimeout
.
You can use the following to achieve the desired effect:
$(document).ready(function() {
var timeout,
$search_box = $('#my_search_box');
$search_box.keyup(function() {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
search();
}, 1000);
});
function search() {
var search_txt = $search_box.val();
}
});
Here's what's happening:
We assign the setTimeout
timer to a variable, which must be declared above your keyup function, and check that variable each time keyup
fires. If there's an existing setTimeout
in progress, clear it out so that it won't fire the search()
function and create a new timer set to wait a specified number of milliseconds (1000 in my example).
See the following JSFiddle for demo: http://jsfiddle.net/highwayoflife/WE4Fr/