Implement Jquery Auto Complete

Jquery Auto Complete

In this article we will show you how to use auto complete of jQuery. Auto complete widget provides suggestions while you type into the field. Here we are going to show you an example that how to implement auto complete and how we can customize it as per our requirement.

In the below example, we have 3 different objects in an array:
 
var data = [{
label: "Code",
value: "http://www.codehotfix.com"
},
{
label: "Hotfix",
value: "http://www.codehotfix.com"
},
{
label: "Code Hotfix",
value: "http://www.codehotfix.com"}
];
$(function () {
$("#idOfSearchTextBox").autocomplete({
source: function (request, response) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(data, function (item) {
return matcher.test(item.label);
}));
},
select: function (event, ui) {
$("#idOfSearchTextBox").val(ui.item.label);
window.location.href = ui.item.value;
}
});
});

hotfix

If you type “h” in the textbox of id idOfSearchTextBox, you will only see Hotfix in the suggestion. If this is what you want you can end stop here.

What if you want all results that include “h” like in our case, you expect “Hotfix” and “Code Hotfix” both. For this you just have to change the matcher.

var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), “i”);

auto complete

Including “^” in RegExp means you want only those that starts with the word. When I was working on application, I found one of the limitations of autocomplete that if you are using this matcher:

var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");

And suppose you have array like:

var array = {‘Ar’,’Rh’}

and you type “r” in textbox that the first result that came is “Ar” not “Rh”. After spending hours I found a fix for this.

auto complete

var reqTerm = $.ui.autocomplete.escapeRegex(term)
, startsWithMatcher = new RegExp("^" + reqTerm, "i")
, startsWith = $.grep(data, function (item) {
return startsWithMatcher.test(item.label || item.value || item);
})
, containsMatcher = new RegExp(reqTerm, "i")
, contains = $.grep(data, function (item) {
return $.inArray(data, startsWith) < 0 && containsMatcher.test(item.label || item.value || item);
});
// This part of code will remove the startswith item from contains list before concat. If you don’t remove it, then search result will be shown twice in the list.
for (var i = 0; i < contains.length; i++) {
var obj = contains[i];
if (startsWith[0].label.indexOf(obj.label) !== -1) {
contains.splice(i, 1);
i--;
}
}
response(startsWith.concat(contains));

You can refer jQuery API documentation for more operations.

Hope you may found your solution..

 

Leave a Reply

Your email address will not be published. Required fields are marked *