Tuesday, November 2, 2010

jQuery autocomplete with caching and custom value selection

Download jQuery library from jQuery site and its ui plugin for autocomplete from this link http://jqueryui.com/home

Define below function in any your js file. (ex: common.js) and then include it in your page.

/**
* Set autocomplete property
*/
function setAutoComplete(element_id, ajax_url, listener, cache_name, term_length)
{
if (element_id === undefined || ajax_url === undefined) return false;
if (listener === undefined) listener = 'itemselected';
if (term_length === undefined) term_length = 1;
if (cache_name === undefined) cache_name = 'itosa_ac_cache';

var cache = [];
cache[cache_name] = [];

$("#"+element_id).autocomplete({
source: function( request, response ) {
var term = request.term;
if ( term in cache[cache_name] ) {
response( cache[cache_name][ term ] );
return;
}
$(this).addClass('ui-autocomplete-loading');
lastXhr = $.getJSON( ajax_url, request, function( data, status, xhr ) {
cache[cache_name][ term ] = data;
if ( data != null && xhr === lastXhr ) {
response( data );
}
});
},
minLength: term_length,
select: function(event, ui){$('body').trigger(listener,[event,ui]);}
})

return false;
}

When you select item from list it will trigger listener event, you have passed through function parameter "listener".

To access the code

setAutoComplete('search_person','http://example.com/person.php','personselect');
$('body').bind('itemselected',function (event,input_event,ui){
$('#seach_key').val(ui.item.id);
return false;
});