Working with HTML5 Web Forms: Autocompletion and the Datalist Element

Explore two options for adding autocompletion to web forms: the HTML5 datalist element and the jQuery UI autocomplete widget

Dino Esposito

February 3, 2013

10 Min Read
Working with HTML5 Web Forms: Autocompletion and the Datalist Element

Typing is generally a boring activity for computer users and a somewhat difficult task for mobile-device users in particular. However, in some input web forms, typing is precisely what users want and need to do. The canonical example is Google: Nearly everyone types keywords, phrases, or questions into the text box. Google, and search engines in general, help with suggestions as the user types -- a feature known as autocompletion, which deserves special attention from developers and usability experts. Autocompletion is especially helpful in any text box that enables users to search for something. Another scenario where autocompletion improves a web form's usability is when the text box can accept strings only from a range of fixed values. In this case, typing into the field is faster than picking the selection from a potentially long drop-down list.

HTML5 provides some support for autocompletion through the datalist element, which makes selection of an item from a relatively long list a quicker process. Here I'll review syntax and semantics of the datalist element and the support that browsers currently offer for it. I will also discuss several alternatives to datalist that are worth considering because browser support for datalist is at present still limited.

The Datalist Element

The datalist element has a fairly simple syntax and is aimed at listing a set of HTML5 option elements in much the same way that an HTML5 select element does. The difference between select and datalist is in the user interface provided by the browser. The select element has its own UI and uses that to present a list of choices to the user. The datalist element, on the other hand, doesn't have a native UI and only provides options to other HTML5 elements, most notably input elements. Listing 1 shows a typical usage example for a datalist element.

Listing 1: The Markup for a Datalist Element

    USA    UK    Uruguay    Brazil    Russia



As you can see in Listing 1, the syntax of the datalist element is nearly identical to that of a select element. But the input element in HTML5 features a new attribute: the list attribute. If the value assigned to the list attribute of an input element of type text matches a datalist element in the page, the options of the datalist will be used as the only accepted values of the input field.

The UI that results from the use of a datalist element is browser specific. Nearly all browsers tend to display it as a drop-down list placed just under the input field. Figure 1 shows the effect of a datalist element as the user starts typing text in Google Chrome 22.

144828_fig1_html5_datalist_element-sm
Figure 1: The Datalist Element in Action

At present, the latest versions of most popular browsers support the datalist element. Overall, though, the number of browser versions that support the datalist element is relatively small and is significantly fewer than the browser versions that have some HTML5 support. In particular, the datalist is supported in Google Chrome starting with version 20 (at the time of this writing, the latest version of Chrome is 22). The datalist is also supported by Firefox since version 14 and Opera since version 12. The datalist is supported on Internet Explorer (IE) only in the latest version shipped with Windows 8: Internet Explorer 10.

If you use the markup shown in Listing 1, the behavior you get from all browsers is mostly uniform, with a few differences. Looking at Figure 1, you can see that Chrome attempts to match the typed text to the start of the string. At present, Firefox is the only browser that uses a lazy algorithm to match typed text to the list of options. Firefox, in fact, matches the typed text against any substring in any of the listed options. Figure 2 shows a screenshot from Firefox; as you can see, the list of options also includes Russia for a typed text of "u".

144828_fig2_html5_datalist_firefox-sm

Figure 2: The Datalist Element in Firefox 15


The list of options can also take a couple of other slightly different formats. According to the W3C standard, the option element is characterized by a value and, optionally, a label. Listing 2 offers another equally valid format for the list of datalist options.

Listing 2: More Precise Markup for a Datalist Element

                    


In this case, as a developer you can distinguish between display text and value text for each option. Figure 3 show the different output you get from Chrome and other browsers.


144828_fig3_datalist_chrome_labels_values-sm
Figure 3: The Datalist in Chrome When Labels and Values Are Specified

Interestingly, only the value element is taken into account in regard to selection. Once the selection is made, the content of the value attribute is displayed in the input field. The value of the label attribute is used only to format the drop-down menu. This behavior is overall reasonable, but it is the first sign that the datalist element might have some drawbacks.

Datalist and Older Browsers

Using the datalist element is quick and easy, but very few browsers actually support it. Users who pick Firefox or Chrome as their primary browser are relatively safe in the sense that these browsers are self-updating, so that users are likely to have the latest version installed. The same can't be said for IE users -- and the datalist is not recognized under IE9 and earlier versions.

The datalist is not simply a semantic element like header or footer, but it delivers a significant behavior. If a given browser doesn't support the datalist element, as a developer it is your responsibility to ensure that users can have the same experience in some other way. A simple fix consists of embedding a select element in the datalist, as shown in Listing 3.

Listing 3: Embedding a Select Element in the Datalist

                          



Newer browsers that recognize the datalist element will safely ignore the embedded select element; older browsers instead will blissfully skip the datalist element and display a classic drop-down list below the input field. By adding a short script, you can also automatically copy the selection to the text box:


This behavior might be an acceptable compromise for browsers like IE9 and Safari for Windows. But it is also a work-around and, as such, doesn't really make use of the datalist a reassuring practice.    Datalist and Dynamically Changing ContentA third, and probably the most important, drawback of the datalist element is the lack of native support for a dynamically changing list of options. In the implementation of the datalist element, the list of options is considered static. You can certainly use a server-side technology to determine the list of options based on runtime conditions. Likewise, you can use a bit of JavaScript and Ajax to download content from a remote endpoint and create, or update, the datalist element dynamically. With even more work on your part, you can bind the refresh of the options to the onchange event fired by the companion text box.If you can do all these things, where's the problem with datalist elements? To answer this question, let's briefly summarize what we've learned about datalists. Essentially, the datalist offers an out-of-the-box solution to the problem of choosing an item out of a possibly long list. In a long list, typing to restrict the selectable options might be more comfortable than just opening a drop-down list and scrolling to find the item of choice.This general notion of the datalist's purpose clashes with the fact of limited browser support for the datalist element and, more importantly, with the fact that not just any list of options can be embedded in the page. The datalist doesn't support obtaining options from a remote endpoint. Additionally, the datalist doesn't let you take full control over the filtering and display of options. You can hardly style items, for example.Finally, you typically want to display friendly names but select codes corresponding to those names. That's precisely the reason for distinguishing between text and value in the implementation of the select element. As you've seen, the datalist uses only the value field. This makes the datalist an excellent method only when you have long lists of single values -- for example, country names. For lists of, say, persons' names where you want to display the full name but pick up only some (invisible) ID, the datalist element is inadequate.More Practical Forms of AutocompletionThe datalist element is useful in a limited number of scenarios and still needs Modernizr or in-house tricks (like using an embedded select) to work across all browsers. A more practical way to incorporate autocompletion in your web forms -- and the best option, in my opinion -- is to use one of the jQuery UI autocomplete widgets. An autocomplete widget is easy to configure and still requires less code than you would use to simulate a datalist by using a Modernizr polyfill. In addition, an autocomplete widget is open to custom styles and provides a number of events for you to customize its behavior. Because of this, the autocomplete widget works well in scenarios where you want users to choose a name but receive an ID that remains invisible to the UI. Listing 4 provides an example of this type of autocompletion, which operates over a potentially long list of names.Listing 4: Setting Up jQuery UI AutocompletionThe most interesting part of this code is not so much the remote endpoint where the list of suggestions is taken -- that's nothing more than a JSON endpoint coded with whatever technology you prefer. The most intriguing stuff takes place in the select event handler. The autocomplete widget fires the select event when the user makes a selection from the menu. The ui parameter carries the selected data item in its item property. From within the ui.item property you can access all the properties of the selected object. Assume now your server code returns a JSON string like this one: [{"value":"United States","id":"USA","label":"United States"},{"value":"United Kingdom","id":"UK","label":"United Kingdom"}]Now it is up to you to distinguish what is displayed in the drop-down menu (the label property), what is selected in the text box (the value property), and what remains invisible but uniquely identifies the selected object (the id property).What if you want to make the label a bit more stylish? Up until jQuery UI 1.8.4, to accomplish this, all you needed to do was to add some HTML formatting to the label property. With newer versions of the jQuery UI library, this is no longer possible; you now need the code shown in Listing 5. (The details of this hack can be easily found on Stackoverflow.com.)Listing 5: Formatting the Autocomplete Drop-Down Menu$("#country") .autocomplete( { ... } ) .data("autocomplete")._renderItem = function (ul, item) { return $("") .data("item.autocomplete", item) .append("" + item.label + "") .appendTo(ul); };Autocomplete ChoicesThe datalist element is an interesting new feature of HTML5, though until recently it has been a bit neglected by browser vendors. The datalist opens up interesting scenarios, but its overall design appears somewhat incomplete. For this reason, I believe that the datalist element does not as yet provide a full-fledged autocomplete functionality. You still will likely need to use a widget for compatibility with older browsers. Thus, at least for the time being, I advise using the jQuery UI autocomplete widget.Learn More About Working with HTML5 Web FormsSimplify Web Form Validation Using HTML5 Working with HTML5 Web Forms: Autofocus and Placeholder Attributes Working with HTML5 Web Forms: Handling Dates and Other Input Types Dino Esposito is a trainer and consultant specializing in web, social, and mobile integrated architecture and effective code design principles and practices. He's the author of Programming Microsoft ASP.NET 4 and Programming Microsoft ASP.NET MVC3 (Microsoft Press).Twitter: @desposBlog: http://weblogs.asp.net/despos/</select></span></p>

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like