Using Autocomplete On Select Elements

Modifying the jQuery UI autocomplete widget to support using select options as a data source.

HTML

<label for="autocomplete">Items:</label>
<select id="autocomplete">
    <option>First Item</option>
    <option>Second Item</option>
    <option>Third Item</option>
    <option>Fourth Item</option>
</select>

CSS

body {
  font-size: 0.8em;
}

JavaScript

(function($, undefined) {

  // Add support to the autocomplete widget
  $.widget("app.autocomplete", $.ui.autocomplete, {

    _create: function() {

      if (this.element.is("select")) {

        // If "this.element" is a select,
        // then we store a reference to it in
        // "original" and add the input element
        // that autocomplete expects.
        var self = this;
        this.original = this.element.hide();
        this.element = $("<input/>").insertAfter(this.original);

        // Setup the source function that reads
        // potential autocomplete items from the
        // select options.
        this.options.source = function(request, response) {
          var filter = $.ui.autocomplete.filter,
            $options = self.original.find("option"),
            result = $options.map(function() {
              return $(this).val();
            });
          response(filter(result, request.term));
        };

      }

      // Finish creating the autocomplete as usual.
      this._super("_create");

    },

    _destroy: function() {
      this._super("_destroy");
      this.element.remove();
      this.original.show();
    }

  });

})(jQuery);

$(function() {
  $("#autocomplete").autocomplete();
});