jQuery UI Autocomplete use startsWith

I'm using the jQuery UI Autocomplete with a local datasource (source: myArray). I want the autocomplete to propose only the results that start with the string entered instead of the default case-insensitive contains search. Is there a simple solution for this or do I have to provide my custom search/source callback?


Solution 1:

See this:

Match start word:

http://blog.miroslavpopovic.com/jqueryui-autocomplete-filter-words-starting-with-term

He overrides the autocomplete filter method. I use this and it works well.

// 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);
    });
};

Match word:

Match startsWith of any word in the string.

e.g. "LHR london" is matched by "london"

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

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)

Solution 2:

Currently I've done it this way, not sure if there is a better solution:

source: function(request, response) {
    var filteredArray = $.map(orignalArray, function(item) {
        if( item.value.startsWith(request.term)){
            return item;
        }
        else{
            return null;
        }
    });
    response(filteredArray);
},

This approach also made it possible to impose a limit (e.g. 10 items) on the amount of items to be shown.

Solution 3:

you can use Same way into Jquery UI Autocomplete Examples

<script>
$("#autocompleteInputField").autocomplete({
  source: function(request, response) {
          var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
          response($.grep(myArray, function(item){
              return matcher.test(item);
          }) );
      }
});
</script>

OR another way with using $.map method not $.grep

<script>
$("#autocompleteInputField").autocomplete({
  source: function(request, response) {
          var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
          response($.map(myArray, function(item) {
               if (matcher.test(item)) {
                   return (item)
               }
          }));
      }
});
</script>

Solution 4:

I went into the Jqueryui code and switched it there.

If you look in the auto complete section, you will see the following line:

filter:function(a,b){var g=new RegExp(d.ui.autocomplete.escapeRegex(b),"i")

Modify it to the following (beware, this is a global change):

filter:function(a,b){var g=new RegExp("^" + d.ui.autocomplete.escapeRegex(b),"i")