Datalist HTML5: what they are and when to use them

0
530

The ‘ auto is a design pattern in which now all Web users have some familiarity. When you do a search, the search engine automatically suggests the terms. When composing a new e-mail message, the program automatically suggests the recipients. Web developers, however, to implement this functionality, have so far had to resort to a fair amount of Javascript code. One of the new HTML5 elements, <datalist>on the other hand, makes the auto-completion functionality native to the web.

In this article, I will explain what datalists are when it is appropriate to use them, their limitations and what to do for browsers that do not support them. Let’s begin.

Create datalist

To check how datalists work, let’s start with a typical text input:

<pre class=”brush: php; html-script: true”>
<label for = “favorite_team”> Favorite Team: </ label>
<input type = “text” name = “team” id = “favorite_team”>
</pre>

The field allows the user to enter the name of his favorite team. By default, the user will not be given additional help to complete the field. But using a datalist, we can provide a list of options that the user can select to complete the field. To do this, we first define a datalist with an option element ( <option>) for each suggestion:

<pre class=”brush: php; html-script: true”>
<Datalist>
<option> Detroit Lions </ option>
<option> Detroit Pistons </ option>
<option> Detroit Red Wings </ option>
<option> Detroit Tigers </ option>
<! – etc … ->
</ Datalist>
</pre>

To link a datalist to an input field, we assign an attribute to the input field list. The value of this attribute listshould match the value of the value idwe will assign to the datalist. Here is an example:

<pre class=”brush: php; html-script: true”>
<label for = “favorite_team”> Favorite Team: </ label>
<input type = “text” name = “team” id = “favorite_team” list = “team_list”>
<datalist id = “team_list”>
<option> Detroit Lions </ option>
<option> Detroit Pistons </ option>
<option> Detroit Red Wings </ option>
<option> Detroit Tigers </ option>
<! – etc … ->
</ Datalist>
</pre>

Note that the attribute listof the text field and the attribute idof the datalist contain the same value team_list. This creates the link between the two elements.

That’s enough. No need for Javascript to run a datalist. In figure 1 we can see what a user will see in his browser after inserting the letter ‘D’ in the text field.

Display of a datalist (top left: Internet Explorer 10, top right: Firefox 18, lower left Chrome 24, bottom right: Opera 12)
Display of a datalist (top left: Internet Explorer 10, top right: Firefox 18, lower left Chrome 24, bottom right: Opera 12)

Note: Internet Explorer 10 and Opera 12 do not require the user to type a character before displaying the suggestion, whereas Chrome and Firefox require it.

Elements <option>can also have an attribute value. This is useful when a user may not know the code associated with a specific option. Consider this input field for selecting one of the US states:

<pre class=”brush: php; html-script: true”>
<label for = “state”> State: </ label>
<input type = “text” name = “state” id = “state” list = “state_list”>
<datalist id = “state_list”>
<option value = “AL”> Alabama </ option>
<option value = “AK”> Alaska </ option>
<option value = “AZ”> Arizona </ option>
<option value = “AR”> Arkansas </ option>
<! – etc ->
</ Datalist>
</pre>

In this case, the user will see a list with the full name of the states, but when selecting an item from the list, the text field will be filled with the status code instead of the full name. Here is an example:

Selecting an option from a datalist with the corresponding value (Firefox 18)
Selecting an option from a datalist with the corresponding value (Firefox 18)

The autocomplete attribute

If the look of the datalist in figure 1 and figure 2 is familiar to you, it is because browsers have long implemented an auto-completion mechanism. All browsers offer a mechanism of some kind for saving and retrieving data entered by the user, data on which the autocompletion functionality is based.

Developers can use the attribute autocomplete on the fields of a form to instruct the browser whether or not to attempt to automatically complete the data entered by the user. The possible values are shown in the following code snippet:

<pre class=”brush: php; html-script: true”>
<Form>
<! –
If the automplete attribute is not specified, the field
inherits the value of the form element that is relative to it.
If not specified, the default value for the attribute
autocomplete of the form is set to “on”. </font><font style=”vertical-align: inherit;”>Since
that neither the input field that follows nor the form have
a defined autocomplete attribute, the value “on” will be used.
->
<input type = “text” name = “firstName”>
<! –
The value “on” indicates that the browser can save
and remember the value entered for the future, and that it can
provide suggestions for completion.
->
<input type = “text” name = “address” autocomplete = “on”>
<! –
The value “off” tells the browser not to save the value
entered for the field and not to offer suggestions for the
completion based on the values previously entered.
This way should be followed if the data are particularly sensitive
or if the value will no longer be reused.
->
<input type = “text” name = “secret” autocomplete = “off”>
</ Form>
</pre>

What, then, is the difference between the attribute autocomplete and the datalist? The attribute autocomplete tells the browser whether to provide the user with options for completion based on how much the user has previously entered in a field and whether to save the value entered for the future. Datalists are instead lists of suggestions prepared and provided by the developer that are always displayed, regardless of previous data entry.

Attention to a point. Setting the attribute autocomplete to off prevents displaying the data list on Opera. Here is an example:

<pre class=”brush: php; html-script: true”>
<! –
This datalist will not be shown on Opera because the attribute
autocomplete is set with the value “off”. </font><font style=”vertical-align: inherit;”>Instead it will be shown
on all other browsers.
->
<input type = “text” list = “pets” autocomplete = “off”>
<datalist id = “pets”>
<Option> Cat </ option>
<Option> Dog </ option>
<Option> Hamster </ option>
<Option> Turtle </ option>
</ Datalist>
</pre>

Other types of input

While autocompletion is traditionally associated with text fields, datalists can also be used on some of the new input types defined in HTML5. Let’s range consider the type input , which allows the creation of a slider form element for the selection of values. By combining an input of this type with a datalist, it is possible to suggest to the user the points defined in a certain range.

For example, the following input asks the user to provide a value between $ 5 and $ 200 for a donation:

<pre class=”brush: php; html-script: true”>
<label for=”donation”>Donation Amount (USD):</label>
<input type=”range” name=”donation” id=”donation” list=”donation_list”
step=”5″ min=”5″ max=”200″>
<datalist id=”donation_list”>
<option>25</option>
<option>50</option>
<option>100</option>
<option>200</option>
</datalist>
</pre>

The following images show the display of type input range, respectively, on Chrome 24 and Internet Explorer 10.

An input range with datalist (Chrome 24)
An input range with datalist (Chrome 24)
An input range with datalist (Internet Explorer 10
An input range with datalist (Internet Explorer 10

As you can see, each browser shows a thin marker for each option defined in the datalist. In addition, Chrome hooks the slider to these default values when the user moves the same slider next to them.

Unfortunately, at the moment, Internet Explorer and Chrome are the only browsers that support datalist on type inputs range. Figure 5 shows datalist support on the most common input types in modern browsers.

Support on datalist browsers on the various types of form input
Support on datalist browsers on the various types of form input

When to use datalist

Since datalists do not offer an automatic mechanism to require the user to select a defined option, they are particularly suitable for inputs that can accept any value.

As a result, the example of American states does not lend itself to datalist use because there is a limited set of valid values that the user must provide. For similar cases, it is better to rely on a drop-down menu (select) because it forces to make a selection.

An exception can be represented by input with a large number of valid options. For example, let’s consider a typical drop-down menu for selecting a country like the one shown in figure 6.

A drop-down menu for selecting a country
A drop-down menu for selecting a country

This list is problematic for the user because it forces him to search through hundreds of options to find the right one. An autocompletion feature is in this suitable scenario because the user can quickly filter the list by entering one or two characters in the field.

Here’s how the selection of a nation can be implemented through the use of a datalist:

<pre class=”brush: php; html-script: true”>
<label for=”country”>Country:</label>
<input type=”text” id=”country” list=”country_list”>
<datalist id=”country_list”>
<option value=”AF”>Afghanistan</option>
<option value=”AX”>Åland Islands</option>
<option value=”AL”>Albania</option>
<option value=”DZ”>Algeria</option>
<!– more –>
</datalist>
</pre>

The figure below shows what appears when the user types the ‘U’ character:

A datalist-based approach for a country selection field
A datalist-based approach for a country selection field

Force the entry of a value

While datalists do not natively allow you to request that an option be selected, we can easily add a validation mechanism that can do such a thing. For example, the code we present below uses the HTML5 validation APIs to add this functionality:

<pre class=”brush: php; html-script: true”>
// Trova tutti gli input nel DOM che sono collegati
// a una datalist attraverso l’attributo list
var inputs = document.querySelectorAll(‘input[list]’);

for (var i = 0; i < inputs.length; i++) {
// Quando il valore del campo cambia…
inputs[i].addEventListener(‘change’, function() {
var optionFound = false,
datalist = this.list;
// Determina se esiste un’opzione con il valore corrente del campo di input.
for (var j = 0; j < datalist.options.length; j++) {
if (this.value == datalist.options[j].value) {
optionFound = true;
break;
}
}
// Usa la funzione setCustomValidity della API di validazione HTML5
// per fornire un feedback all’utente nel caso in cui un valore
// non esista nella datalist
if (optionFound) {
this.setCustomValidity(”);
} else {
this.setCustomValidity(‘Please select a valid value.’);
}
});
}
</pre>

The validation API is implemented on all browsers that support datalist. So, if datalists work, validation should also work. Now, when the user tries to send a form with an input that has an associated datalist and has not selected an option, he will see the error message shown in Figure below.

alidation API error message (Internet Explorer 10)
alidation API error message (Internet Explorer 10)

It is important to note that the HTML5 form validation API does not eliminate the need for server-side validation. Users using older browsers will not have this client-side validation API available from HTML5, and savvy users will also be able to subvert the scripting structure.

In short, this approach, while working in modern browsers, presents very serious usability problems for those who use older browsers that do not support these mechanisms. These users are told that they must select a valid value, but if their browser does not support datalist, they will not be able to see the options. So, if you plan to follow this approach, make sure the interface works on all browsers. This can be achieved by first checking if the browser supports datalists and then offering an alternative mechanism in the form of polyfill.

Browsers that do not support datalist

By the time we write this article, the datalists associated with text fields are supported by Internet Explorer 10, Firefox 4+, Chrome 20+ and Opera. A scenario that unfortunately leaves a large number of users outside.

Unlike other new features of HTML5, in most cases, there is no need for extra work in browsers that do not support datalist. By default, the list of options that is defined is made up of mere suggestions; therefore, users browsing with browsers that do not support datalist will simply fill out the text field without making any suggestions.

However, fallback options can be provided to provide a full experience for those who use browsers without support.

Offer alternative HTML content

An option, popularized by Jeremy Keith, is to take advantage of the fact that browsers that do not support datalist will still show the child elements to the user. Here’s how the nation selection datalist could be modified to provide an alternative in the form of pull-down menus (select):

<pre class=”brush: php; html-script: true”>
<label for=”country”>Country:</label>
<datalist id=”country_list”>
<select name=”country”>
<option value=”AF”>Afghanistan</option>
<option value=”AX”>Åland Islands</option>
<option value=”AL”>Albania</option>
<option value=”DZ”>Algeria</option>
<option value=”AS”>American Samoa</option>
<!– more –>
</select>
If other, please specify:
</datalist>
<input type=”text” name=”country” id=”country” list=”country_list”>
</pre>

For users who use browsers with datalist support, the interface will not change, but users working with unattended browsers will now see a drop-down menu (select) with country options and a text field that they can use to enter any value. The result is visible below:

An alternative with drop-down menus for datalist (Internet Explorer 9)
An alternative with drop-down menus for datalist (Internet Explorer 9)

Use a polyfill

A feature that the drop-down based alternative does not offer is the autocomplete mechanism that datalists present natively. If this is important for the datalist you plan to use, a second alternative is to use a polyfill that emulates the behavior of the datalist.

To get started, you first need to determine if the user’s browser supports datalist. The popular feature detection library Modernizr provides a system for carrying out the verification, as we can see below:

<pre class=”brush: php; html-script: true”>
if (Modernizr.input.list) {
//Il browser supporta l’attributo ‘list’ e le datalist.
} else {
//Il browser non supporta né l’attributo ‘list’ né le datalist.
}
}
</pre>

Using this approach, we can now take advantage of a polyfill to emulate datalists for users with browsers that do not support datalist. There are many polyfills available, but I prefer to use the jQuery UI autocomplete widget. The following code shows the implementation of the polyfill:

<pre class=”brush: php; html-script: true”>
var datalist,
listAttribute,
options = [];
// Se il browser non supporta l’attributo ‘list’…
if (!Modernizr.input.list) {
// Per ogni campo di testo con un attributo ‘list’…
$(‘input[type=&quot;text&quot;][list]’).each(function() {
// Trova l’id della datalist
// Usando ‘this’, trova la datalist che &egrave; associata all’input
listAttribute = $(this).attr(‘list’);
datalist = $(‘#’ + listAttribute);
// Se il campo di testo ha una datalist associata
if (datalist.length &gt; 0) {
options = [];
// Crea la lista di opzioni da passare al widget per l’autocompletamento.
datalist.find(‘option’).each(function() {
options.push({ label: this.innerHTML, value: this.value });
});
// Trasforma l’input in un widget jQuery UI.
$(this).autocomplete({ source: options });
}
});
// Rimuove tutte le datalist dal DOM.
$(‘datalist’).remove();
}
</pre>

The figure below shows the example of the list with the nations on Safari with the jQuery UI autocomplete widget:

The polyfill for datalist based on jQuery UI (Safari)
The polyfill for datalist based on jQuery UI (Safari)

<pre class=”brush: php; html-script: true”>
<input type=”text” id=”autocomplete”>
<script>
var options = [‘Badger’, ‘Bat’, ‘Cat’, ‘Cheetah’, ‘Crocodile’, ‘Deer’, ‘Donkey’,
‘Elephant’, ‘Fish’, ‘Frog’, ‘Giraffe’, ‘Gorilla’];
$(‘#autocomplete’).autocomplete({
source: function (req, responseFn) {
var term = $.ui.autocomplete.escapeRegex(req.term),
matcher = new RegExp(‘^’ + term, ‘i’),
matches = $.grep(options, function (item) {
return matcher.test(item);
});
responseFn(matches);
}
});
</script>
</pre>

Older versions of Internet Explorer

In order for any polyfill for datalist to work on older versions of Internet Explorer, two additional steps are required.

The option elements

The first: Internet Explorer 9 and earlier all require elements to option be children of elements select. If they are not, they will not be recognized, and will not be visible to the polyfill.

Fortunately, it is something that is easy to overcome. Using conditional comments, we can insert an element select around the options only for those versions of Internet Explorer. Here is the example:

<pre class=”brush: php; html-script: true”>
<datalist>
<!–[if IE]><select><!–<![endif]–>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
<!- etc –>
<!–[if IE]><select><!–<![endif]–>
</datalist>
</pre>

Internet Explorer 9 and earlier will now identify the options correctly. Internet Explorer 10 will not be touched by this trick because conditional comments have been removed from this browser’s parser . Obviously, all other browsers other than IE will ignore conditional comments.

HTML5 Shiv

On Internet Explorer 8 and earlier, unrecognized HTML elements can not contain child elements. Therefore, even if the datalist options are enclosed within a select, they will not be recognized.

Also in this case there is fortunately a very simple solution. The popular Shiv HTML5 library allows unknown elements for Internet Explorer 6-8 to have child elements. The library is included in Modernizr; just make sure that the “html5 shiv” checkbox is selected when you configure your library download.

Datalist restrictions

Although datalists are perfect for adding automatic suggestions to text fields, they have the defect of not being customizable as many modern web applications require. For example, it is not possible to do these things with a datalist:

use CSS to change its display options;
check the positioning of the list;
check the number of characters entered before the browser shows the results to the user;
check and fix what is a match and what is not (case sensitivity, correspondence at the beginning vs. in any position, etc.);
connect input to a server-side data source.
This means that if you need any of these features, you will need to resort to a more robust autocomplete solution. The jQuery UI autocomplete widget allows you to do all the things listed above and even more. Among other things, it also supports Internet Explorer up to version 7 without the need for polyfill. For more information on this widget, you can consult the demos and API documentation (the widget only handles text fields, so it will not be useful for other types of input such as type rangeor color).

Conclusions

Datalists are a quick and native way to show suggestions to the user. Since the options are mere suggestions, for many situations it will not be necessary to provide an alternative for browsers without support; users of these browsers will not see suggestions. That’s all.

For situations where you want to provide a functional datalist to all users, we can verify the functionality support and offer a polyfill-based alternative.

If datalists are excellent for submitting suggestions, they are limited in the features they offer. If you need a more robust autocomplete solution, the jQuery UI widget is a good place to start.

LEAVE A REPLY

Please enter your comment!
Please enter your name here