jQuery UI Autocomplete Widget Extension

jQuery UIMany of my personal and professional projects use the jQuery UI Autocomplete widget. Customers love being able to type a search term and have their choices limited to only those items in which they’re interested. The base widget, however, doesn’t provide all the functionality I need and ad hoc customizations have become tedious. So, I’ve decided to write an extension using the Widget Factory that brings together the features I use most often. My AutocompletePro widget is definitely a work in progress, but you can grab the latest version from GitHub.


Live Demo!

This is a jQuery UI widget and may not be suitable for some mobile devices. A jQuery mobile version will soon be posted to my development site!

Delete the current input text and start typing the title of one of your favorite jazz albums, perhaps “Jazz Samba”. You can also type in an artist’s name like Miles Davis or the year 1958. Then make a selection from the available recordings.


AutocompletePro adds several new options to the base Autocomplete:

  • autodrop: defines if the menu should open on focus
  • categoryfield: what field to use as the category
  • categorize: defines if the menu should be categorized
  • defaultvalue: sets the initial value
  • datasource: replaces the base source option
  • filter: sets a filter on the data source records
  • filtereddatasource: read only – the datasource that is being used by the widget
  • itemsshown: limits the number of hits returned
  • searchfields: array of fields names to be searched

And two new methods:

  • value: returns the selected item object
  • selectitem: selects an item given a set of elements

Demo Code GitHub

The datasource for this demo is structured as follows:

 
var data.items = [{ "category": "Traditional", "artist": "Benny Goodman", "label": "Live at Carnegie Hall 1938 [Live]", "year": "1950" },
  ...
{ "category": "Bebop", "artist": "Charlie Parker", "label": "Best of the Complete Savoy and Dial Studio Recordings [Compilation]", "year": "2002" }]

And the widget is created with these options:

$("#widgetbox").autocompletepro({
        autoFocus: true,
        itemsshown: 10,
        datasource: data.items,
        autodrop: true,
        searchfields: ["label", "artist", "year"],
        categorize: true,
        defaultvalue: [{ "artist": "Miles Davis", "label": "Kind of Blue" }],
        categoryfield: "category",
        filter: [{ "category": "Traditional" }, { "category": "Latin" }, { "category": "Cool" }, { "category": "Fusion" }, { "category": "Bebop" }]
});

Tagged with:
Posted in JavaScript and jQuery
Advertisement