Tuesday, April 24, 2012

Delaying an autocomplete jQuery search

I recently implemented an autocomplete function on a site, using jQuery to update the results and a JsonResult controller to get the actual data.  When the content of a search box changed (using event trigger onkeyup), it would perform a search on the contents of that text box.  I've gone a few steps further and split the text box on spaces and commas, to create a wildcard search, but that's not the point of this post.

The issue I saw is that a new call to the database or cache was being carried out with every keypress.  This was a problem.  So I found some code on http://jsbin.com/ebela4/8/edit#javascript,html and adapted it slightly.  Here it is:


var delay = 600;
var isLoading = false;
var isDirty = false;

function AutoCompleteChange() {
if (!isLoading) {
// This only performs a search if four or more characters have been
// entered. Change the number to change this restriction.
if ($("#txtSearch").val().length >= 3) {
isLoading = true;
setTimeout(function () {
isLoading = false;
if (isDirty) {
isDirty = false;
// Perform actual search
// INSERT YOUR CODE HERE
}
}, delay);
};
};  
};

No comments:

Post a Comment