Friday, April 26, 2013

jquery autocomplete source function

For e.g., if the user types john smith in the inputBox, and you want to return all the elements which contain either john or smith or both, then use the following code : 
 
$( "#inputBox" ).autocomplete({
source: function (request,response) {
var terms = request.term.trim().replace(/\s+/g,' ').split(" "); //Now terms is an array ['john','smith']
var respData = {}; 
terms.forEach( function(term) { 
lookUpArray.forEach(  function (lookUpElem) {
var regexp = new RegExp(term, "gi");
if(lookUpElem.match(regexp)) {
respData[lookUpElem] = 1;

});
});
var results = [];
for(var k in respData) results.push(k);
response(results);
}
});

lookUpArray is a global variable here - if it contains ['john dao' ,'smith dao', 'john smith', 'singh bone'] - then the first 3 elements will be returned for the query john smith.

No comments:

Blog Archive