A jQuery UI Combobox: Under the hood

Update on 2010-08-17: This article was updated to reflect the changes to the combobox code in jQuery UI 1.8.4

The jQuery UI 1.8 release brings along the new autocomplete widget. An autocomplete adds a list of suggestions to an input field, displayed and filtered while the user is typing. This could be attached to a search field, suggesting either search terms or just matching results for faster navigation. But what if there is a fixed list of options, usually implemented as a standard HTML select element, where the ability to filter would help users find the right value way faster?

That's a "combobox." A combobox works like a select, but also has an input field to filter the options by typing. jQuery UI 1.8 actually provides a sample implementation of a combobox as a demo. In this article, we'll look under the hood of the combobox demo, to explore both the combobox widget and the autocomplete widget that it uses.

Let's starts with the initial markup:

[html] [/html]

Nothing special there, just a label and a select element with a few options.

The code to apply the combobox widget to the select is quite simple, too:

[js]$("select").combobox(); [/js]

Let's look at the code for this combobox widget. First, the full code, to give you an overview. We'll dig into the details step-by-step afterwards.

[js]$.widget( "ui.combobox", { _create: function() { var self = this; var select = this.element.hide(), selected = select.children( ":selected" ), value = selected.val() ? selected.text() : ""; var input = $( "" ) .insertAfter(select) .val( value ) .autocomplete({ delay: 0, minLength: 0, source: function(request, response) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" ); response( select.children("option" ).map(function() { var text = $( this ).text(); if ( this.value && ( !request.term || matcher.test(text) ) ) return { label: text.replace( new RegExp( "(?![^&;]+;)(?!< [^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1"), value: text, option: this }; }) ); }, select: function( event, ui ) { ui.item.option.selected = true; self._trigger( "selected", event, { item: ui.item.option }); }, change: function(event, ui) { if ( !ui.item ) { var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ), valid = false; select.children( "option" ).each(function() { if ( this.value.match( matcher ) ) { this.selected = valid = true; return false; } }); if ( !valid ) { // remove invalid value, as it didn't match anything $( this ).val( "" ); select.val( "" ); return false; } } } }) .addClass("ui-widget ui-widget-content ui-corner-left"); input.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "
  • " ) .data( "item.autocomplete", item ) .append( "" + item.label + "" ) .appendTo( ul ); }; $( "" ) .attr( "tabIndex", -1 ) .attr( "title", "Show All Items" ) .insertAfter( input ) .button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }) .removeClass( "ui-corner-all" ) .addClass( "ui-corner-right ui-button-icon" ) .click(function() { // close if already visible if (input.autocomplete("widget").is(":visible")) { input.autocomplete("close"); return; } // pass empty string as value to search for, displaying all results input.autocomplete("search", ""); input.focus(); }); } });[/js]

    Let's break this down, piece by piece:

    [js]$.widget( "ui.combobox", { _create: function() { // all the code } });[/js]

    This defines a new widget, in the ui namespace (don't use this for your own widgets, it's reserved for jQuery UI widgets) and adds the only method, _create. This is the constructor method for jQuery UI widgets, and will be called only once. In versions prior to 1.8 it was called _init. The _init method still exists, but it is called each time you call .combobox() (with or without options). Keep in mind that our widget implementation is not complete, as it lacks the destroy method. It's just a demo.

    Coming up next is the creation of an input element and applying the autocomplete to it, with data provided by the select element.

    [js]var self = this; var select = this.element.hide(), selected = select.children( ":selected" ), value = selected.val() ? selected.text() : ""; var input = $("") .insertAfter(select) .val( value ) .autocomplete({ delay: 0, minLength: 0 source: function(request, response) { // implements retrieving and filtering data from the select }, select: function(request, response) { // implements first part of updating the select with the selection }, change: function(event, ui) { // implements second part of updating the select with the selection }, }) .addClass("ui-widget ui-widget-content ui-corner-left");[/js]

    It starts with a few variable declarations: var self = this will be used inside callbacks below, where this will refer to something else. The var select references the select element on which the combobox gets applied. To replace the select with the text input, the select is hidden.

    The selected and value variables are used to initialized the autocomplete with the current value of the select.

    An input element is created from scratch, inserted after the select element into the DOM, and transformed into an autocomplete widget. All three autocomplete options are customized:

    • delay specifies the amount of time to wait for displaying data between each key press, here set to zero as the data is local
    • minLength is set to 0, too, so that a cursor-down or -up key press will display the autocomplete menu, even when nothing was entered.
    • source provides the filtered data to display

    Let's break down the source implementation:

    [js]source: function(request, response) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" ); response( select.children("option" ).map(function() { var text = $( this ).text(); if ( this.value && ( !request.term || matcher.test(text) ) ) return { label: text.replace( new RegExp( "(?![^&;]+;)(?!< [^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1"), value: text, option: this }; }) ); },[/js]

    There is a bit of matching and mapping involved here: At first, a regular expression object is defined, based on the entered term, escaped with the help of the $.ui.autocomplte.escapeRegex utility method. This regex gets reused in the function below. The response argument, a callback, gets called, to provide the data to display. The argument passed is the result of the call to select.find("option").map(callback). That finds all option elements within our original select, then maps each option to a different object, implemented in another callback passed to the map method.

    This callback will return undefined, thereby removing an item, when a search term is present and the text of the option doesn't match the entered value. Otherwise (no term, or it matches), it'll return an object with three properties:

    • label: based on the text of the option, with the matched term highlighted with some regexing (another example of a write-only regular expression)
    • value: the unmodified text of the option, to be inserted into the text input field
    • option: the option element itself, to update the select (via the selected-property) or to pass on in custom events

    The label and value properties are expected by the autocomplete widget, the option property has an arbitrary name, used here only by the combobox widget.

    Before, I mentioned that the combobox widget customizes all three autocomplete options, but there were actually five options specified. The fourth and fifth properties, select and change, are event. This is the select implementation:

    [js]select: function(event, ui) { ui.item.option.selected = true; self._trigger( "selected", event, { item: ui.item.option }); },[/js]

    The ui.item argument refers to the data we provided in the source option. Via the ui.item.option property we can update the underlying select to the selected item, as well as triggering a selected events for further customization of the combobox widget.

    To cover the case where no selection is made, the change event is used:

    [js]change: function(event, ui) { if ( !ui.item ) { var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ), valid = false; select.children( "option" ).each(function() { if ( this.value.match( matcher ) ) { this.selected = valid = true; return false; } }); if ( !valid ) { // remove invalid value, as it didn't match anything $( this ).val( "" ); select.val( "" ); return false; } } },[/js]

    Here the entered value is used to try and match a selection. If the value doesn't match anything, it'll get removed, and the underlying select is set to an empty value, too.

    The next block customizes the _renderItem method of the underlying autocomplete. This is necessary to output the highlighting on each row, as autocomplete by default will escape any html.

    [js]input.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "
  • " ) .data( "item.autocomplete", item ) .append( "" + item.label + "" ) .appendTo( ul ); };[/js]

    And finally, the last block creates the button that opens the full list of options:

    [js]$( "" ) .attr( "tabIndex", -1 ) .attr( "title", "Show All Items" ) .insertAfter( input ) .button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }) .removeClass( "ui-corner-all" ) .addClass( "ui-corner-right ui-button-icon" ) .click(function() { // close if already visible if (input.autocomplete("widget").is(":visible")) { input.autocomplete("close"); return; } // pass empty string as value to search for, displaying all results input.autocomplete("search", ""); input.focus(); });[/js]

    Another element is created on-the-fly. It gets tabIndex="-1" to take it out of the tab order, as it's mostly useful for mouse interactions. Keyboard interaction is already covered by the input element. It gets a title attribute to provide a tooltip and is inserted after the input element into the DOM. A call to .button() with some options together with a bit of class-mangling transforms the button into a Button widget that displays a down-arrow icon with rounded corners on the right (the input has rounded-corners on the left).

    Finally a click event is bound to the button: If the autocomplete menu is already visible, it gets closed, otherwise the autocomplete's search method is called with an empty string as the argument, to search for all elements, independent of the current value within the input. As the input handles keyboard input, it gets focused. Having focus on the button would be useless or would require duplicate keyboard interaction that the input already supports.

    And that's it! We can see that the autocomplete widget is flexible enough to allow all this with option customization, events, and calling a few methods. We don't have to "subclass" autocomplete (creating a new widget with the autocomplete as the parent prototype instead of $.widget). Instead, we can make the combobox mostly independent of any internal or private autocomplete methods. For the full experience and latest version, check out the combobox demo on the jQuery UI site.



    Responsive Menu
    Add more content here...