Tuesday, March 19, 2013

Finishing the jQuery UI AutoComplete ComboBox Demo

jqueryui-select-combobox
If you worked with the jQuery UI Autocomplete, you may have noticed the demo for the combobox which replaces a HTML select box with a autocomplete/button widget that looks like a select box but provides type ahead features. The data source for the autocomplete is the select box. You're just enhancing the user experience with the type ahead. However, there is a note on the demo indicating it is not complete. It also provides a link with more details about the implementation that also states its not complete. Well, I really needed a complete version so took the time to package it up and figured I'd share what I built in case you're in the same place I was.

The demos are not exceptionally far from complete. The biggest change I made was to remove setting the value of the combobox from the _create() function and moving it to a value() function so that it could be used to get/set the combobox after it was initialized. I also added a change trigger in the autocomplete change callback. Finally, I put a wrapper element around the whole thing and added a few classes to enable better control of the styling.

You might ask why I moved transferring the value from the select box to the widget when it is initialized. I have several arguments which may not be applicable to other use cases (or you just feel differently). Either way, here they are:


  1. Unlike other input fields, the select box will pick the first entry even if you don't explicitly set it. You generally have to add a empty item or explicitly set selectedIndex to -1 to prevent this behavior. I want to only have the list of valid choices in the box and did not want the combobox to initialize with the first item in the list (nothing selected is implicitly null/blank/empty).

  2. I want to interact with the widget not the select box so using the value() function makes sense and is consistent with other jQuery UI widgets (spinner, slider, etc).

  3. The widget will most likely be bound to something I plan to get/set in a database so the initial value of the select box is irrelevant and will be overridden shortly after initializing the widget.



  4. The third point is really my biggest reason for having the value() function and skipping setting it during the creation phase. If your working with an MVC library like Backbone, Knockout, etc, then you'll be binding the widget to some data source that will get/set it via some kind of event triggering mechanism. Anything that is there when you create the widget won't be there shortly after creating it because the binding will set it to something useful.

    I have the current source on my GitHub jQuery UI extension repository (JS/CSS). You can also view the demos for examples. The pertinent one shows how the value function is used to get/set the combobox after its been initialized.