views:

41

answers:

1

Hi,

I am using jqueryui autocomplete widget for autocompleting a 'country' field but I am facing an issue. Suppose the user enters "in", I want the jqueryui to list countries like 'india', 'indonesia' which start with 'in', but it also lists the countries which have 'in' somewhere in the name (like: argentina). How can I solve this issue?

jQuery(".autocomplete").autocomplete({
    source: CountrySuggestions, //CountrySuggestions is an array in javascript containing the list of countries
    minLength: 2
});

Akshey

A: 

Unfortunately, it appears as though the jQueryUI Autocomplete was made to not allow this on an array source. You can, however, hook the plugin's _initSource function to force a "starts with" regular expression token ( ^ ) on the search as below.

I think this was probably overlooked because the majority of its usage was thought to be in the remote retrieval. Either way, not a pretty fix, but due to the regex stripping function, it's the only solution that came to mind.

$.ui.autocomplete.prototype._initSource = function() {
  var array,
    url;
  if ( $.isArray(this.options.source) ) {
    array = this.options.source;
    this.source = function( request, response ) {
      // escape regex characters
      var matcher = new RegExp( "^"+$.ui.autocomplete.escapeRegex(request.term), "i" );
      response( $.grep( array, function(value) {
        return matcher.test( value.label || value.value || value );
      }) );
    };
  } else if ( typeof this.options.source === "string" ) {
    url = this.options.source;
    this.source = function( request, response ) {
      $.getJSON( url, request, response );
    };
  } else {
    this.source = this.options.source;
  }
};

$("#countries").autocomplete({
  source: ["India","Indonesia","Argentina"],
  minLength: 2
});
Lance May
JSBin: http://jsbin.com/ekiga4
Lance May
Thanks for the solution
Akshey