jQuery UI Autocomplete - Filter words starting with term

Published on Saturday, June 23, 2012

I had an interested problem with jQuery UI Autocomplete yesterday. The client required that the search / filtering should be done from the beginning of the word only. By default, jQuery UI Autocomplete filters through the list matching the term in the middle of the word.

There are solutions with using function as an Autocomplete source. It would be OK if we weren't using jqAuto Knockout binding by RP Niemeyer which already takes over the Autocomplete source option.

The solution was pretty easy though. After searching thru jQuery UI's source, I found the filter method used just for that. All that needs to be done is replacing that function with this:

// Overrides the default autocomplete filter function to
// search only from the beginning of the string
$.ui.autocomplete.filter = function (array, term) {
  var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
  return $.grep(array, function (value) {
    return matcher.test(value.label || value.value || value);

This is actually the copy of the default jQuery UI's filter method with a single change. Regex is prefixed with "^" sign which matches the beginning of the string.

Please note that this is a global change. It will affect all autocomplete boxes on your page.

Here's a fiddle for that, if you want to play around (just try commenting / uncommenting the filter method):

comments powered by Disqus