Uncategorized

auto compelete combobox nested

http://www.learningjquery.com/2010/06/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.4The 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 HTMLselect 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:

  1. <label>Your preferred programming language: </label>
  2. <select>
  3.   <option value=”a”>asp</option>
  4.   <option value=”c”>c</option>
  5.   <option value=”cpp”>c++</option>
  6.   <option value=”cf”>coldfusion</option>
  7.   <option value=”g”>groovy</option>
  8.   <option value=”h”>haskell</option>
  9.   <option value=”j”>java</option>
  10.   <option value=”js”>javascript</option>
  11.   <option value=”p1″>perl</option>
  12.   <option value=”p2″>php</option>
  13.   <option value=”p3″>python</option>
  14.   <option value=”r”>ruby</option>
  15.   <option value=”s”>scala</option>
  16. </select>

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:

JavaScript:

  1. $(“select”).combobox();

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.

JavaScript:

  1. $.widget( “ui.combobox”, {
  2.   _create: function() {
  3.     var self = this;
  4.     var select = this.element.hide(),
  5.       selected = select.children( “:selected” ),
  6.       value = selected.val() ? selected.text() : “”;
  7.     var input = $( “<input />” )
  8.       .insertAfter(select)
  9.       .val( value )
  10.       .autocomplete({
  11.         delay: 0,
  12.         minLength: 0,
  13.         source: function(request, response) {
  14.           var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), “i” );
  15.           response( select.children(“option” ).map(function() {
  16.             var text = $( this ).text();
  17.             if ( this.value && ( !request.term || matcher.test(text) ) )
  18.               return {
  19.                 label: text.replace(
  20.                   new RegExp(
  21.                     “(?![^&;]+;)(?!<[^<>]*)(” +
  22.                     $.ui.autocomplete.escapeRegex(request.term) +
  23.                     “)(?![^<>]*>)(?![^&;]+;)”, “gi”),
  24.                   “<strong>$1</strong>”),
  25.                 value: text,
  26.                 option: this
  27.               };
  28.           }) );
  29.         },
  30.         select: function( event, ui ) {
  31.           ui.item.option.selected = true;
  32.           self._trigger( “selected”, event, {
  33.             item: ui.item.option
  34.           });
  35.         },
  36.         change: function(event, ui) {
  37.           if ( !ui.item ) {
  38.             var matcher = new RegExp( “^” + $.ui.autocomplete.escapeRegex( $(this).val() ) + “$”, “i” ),
  39.             valid = false;
  40.             select.children( “option” ).each(function() {
  41.               if ( this.value.match( matcher ) ) {
  42.                 this.selected = valid = true;
  43.                 return false;
  44.               }
  45.             });
  46.             if ( !valid ) {
  47.               // remove invalid value, as it didn’t match anything
  48.               $( this ).val( “” );
  49.               select.val( “” );
  50.               return false;
  51.             }
  52.           }
  53.         }
  54.       })
  55.       .addClass(“ui-widget ui-widget-content ui-corner-left”);
  56.     input.data( “autocomplete” )._renderItem = function( ul, item ) {
  57.       return $( “<li></li>” )
  58.         .data( “item.autocomplete”, item )
  59.         .append( “<a>” + item.label + “</a>” )
  60.         .appendTo( ul );
  61.     };
  62.     $( “<button> </button>” )
  63.     .attr( “tabIndex”, -1 )
  64.     .attr( “title”, “Show All Items” )
  65.     .insertAfter( input )
  66.     .button({
  67.       icons: {
  68.         primary: “ui-icon-triangle-1-s”
  69.       },
  70.       text: false
  71.     })
  72.     .removeClass( “ui-corner-all” )
  73.     .addClass( “ui-corner-right ui-button-icon” )
  74.     .click(function() {
  75.       // close if already visible
  76.       if (input.autocomplete(“widget”).is(“:visible”)) {
  77.         input.autocomplete(“close”);
  78.         return;
  79.       }
  80.       // pass empty string as value to search for, displaying all results
  81.       input.autocomplete(“search”, “”);
  82.       input.focus();
  83.     });
  84.   }
  85. });

Let’s break this down, piece by piece:

JavaScript:

  1. $.widget( “ui.combobox”, {
  2.   _create: function() {
  3.     // all the code
  4.   }
  5. });

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 destroymethod. 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.

JavaScript:

  1. var self = this;
  2. var select = this.element.hide(),
  3.   selected = select.children( “:selected” ),
  4.   value = selected.val() ? selected.text() : “”;
  5. var input = $(“<input />”)
  6.   .val( value )
  7.   .autocomplete({
  8.     delay: 0,
  9.     minLength: 0
  10.     source: function(request, response) {
  11.       // implements retrieving and filtering data from the select
  12.     },
  13.     select: function(request, response) {
  14.       // implements first part of updating the select with the selection
  15.     },
  16.     change: function(event, ui) {
  17.       // implements second part of updating the select with the selection
  18.     },
  19.   })
  20.   .addClass(“ui-widget ui-widget-content ui-corner-left”);

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:

JavaScript:

  1. source: function(request, response) {
  2.   var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), “i” );
  3.   response( select.children(“option” ).map(function() {
  4.     var text = $( this ).text();
  5.     if ( this.value && ( !request.term || matcher.test(text) ) )
  6.       return {
  7.         label: text.replace(
  8.           new RegExp(
  9.             “(?![^&;]+;)(?!<[^<>]*)(” +
  10.             $.ui.autocomplete.escapeRegex(request.term) +
  11.             “)(?![^<>]*>)(?![^&;]+;)”, “gi”),
  12.           “<strong>$1</strong>”),
  13.         value: text,
  14.         option: this
  15.       };
  16.   }) );
  17. },

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:

JavaScript:

  1. select: function(event, ui) {
  2.   ui.item.option.selected = true;
  3.   self._trigger( “selected”, event, {
  4.     item: ui.item.option
  5.   });
  6. },

The ui.item argument refers to the data we provided in the source option. Via theui.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:

JavaScript:

  1. change: function(event, ui) {
  2.   if ( !ui.item ) {
  3.     var matcher = new RegExp( “^” + $.ui.autocomplete.escapeRegex( $(this).val() ) + “$”, “i” ),
  4.     valid = false;
  5.     select.children( “option” ).each(function() {
  6.       if ( this.value.match( matcher ) ) {
  7.         this.selected = valid = true;
  8.         return false;
  9.       }
  10.     });
  11.     if ( !valid ) {
  12.       // remove invalid value, as it didn’t match anything
  13.       $( this ).val( “” );
  14.       select.val( “” );
  15.       return false;
  16.     }
  17.   }
  18. },

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.

JavaScript:

  1. input.data( “autocomplete” )._renderItem = function( ul, item ) {
  2.   return $( “<li></li>” )
  3.     .data( “item.autocomplete”, item )
  4.     .append( “<a>” + item.label + “</a>” )
  5.     .appendTo( ul );
  6. };

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

JavaScript:

  1. $( “<button> </button>” )
  2. .attr( “tabIndex”, -1 )
  3. .attr( “title”, “Show All Items” )
  4. .insertAfter( input )
  5. .button({
  6.   icons: {
  7.     primary: “ui-icon-triangle-1-s”
  8.   },
  9.   text: false
  10. })
  11. .removeClass( “ui-corner-all” )
  12. .addClass( “ui-corner-right ui-button-icon” )
  13. .click(function() {
  14.   // close if already visible
  15.   if (input.autocomplete(“widget”).is(“:visible”)) {
  16.     input.autocomplete(“close”);
  17.     return;
  18.   }
  19.   // pass empty string as value to search for, displaying all results
  20.   input.autocomplete(“search”, “”);
  21.   input.focus();
  22. });

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 inputelement. 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 demoon the jQuery UI site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s