We have been using the jQuery UI autocomplete widget almost without fail in our projects. In recent years, our agency has been developing websites for airliners, hotels and travel portals, and all our clients need some kind of facility to display a filtered list of hotels, airports, locations, etc. This kind of use case is a handy fit for the autocomplete widget, since it can query a remote JSON/JSONP data source and display result lists.

It seems, however, that across all our projects we have been repeating a lot of boilerplate code in order to make the widget useable. In particular:

  • If you want to post to the form the actual user's selected value, not the label, you need a separate hidden input to hold it;
  • In cases like location searches, you may need to categorize the results (e.g. hotels, cities, airports)

In order to avoid repetition, I used the magic of the widget factory to extend the widget with a few extra functions. The extended autocompleter:

  • Can categorize results, if your pass it the
    categorize: true
    option (this requires an extra category field in the data source's response);
  • Takes an extra
    option, which it uses to select the hidden input in which to store the selected value;
  • Takes a
    (boolean) and
    (string) option, which it can use to create the hidden input element for you (the element is created as concat([text input id], [holderSuffix]);
  • Clears selection on focus;
  • Takes a
    option, which polyfills the lack of the HTML5 placeholder attribute for older browsers.

ASP.NET Web Forms programmers are more likely to find the holderSelector option more useful than the createHolder/holderSuffix pair. MVC programmers will likely find the latter a better option as it keeps the HTML cleaner.

You can view/download the widget here. Feel free to use it in your own projects. Please drop me a line if you found it useful.

Happy coding!