Where elements accept text input—such as text, url, or search—you can provide a list of helpful suggestions to the user. The browser can offer these based on the user’s previous input (controlled by the previously mentioned autocomplete attribute), but at times you may want to suggest a range of predefined terms. Implement this latter option with the datalist element.
The datalist element contains a list of suggestions, each of which is contained in an option child element (which you should be familiar with from the select element in HTML 4.01). To illustrate what I mean, here’s a short datalist with only a few options:
<datalist id="apes"> <option>Chimpanzee</option> <option>Gorilla, Eastern</option> <option>Gorilla, Western</option> <option>Orangutan</option> </datalist>
The datalist element isn’t rendered on the page and doesn’t have to be close to the input that refers to it; it can be placed anywhere in the markup.
To create an association between the input field into which the user will enter data and the datalist element that holds the suggestions, the former uses the id value of the latter as the value for its own list attribute:
<input type="text" list="apes">
Now when the user types a letter (or sequence of letters), any option element values within the datalist that match that sequence will be displayed in a list of suggestions below the input. From here, the user can choose a matching option. You can see this for yourself in input-types-more.html, as illustrated in Figure 8-3.
This association between the id and list attributes means that multiple inputs can refer to the same datalist element, if required.
In browsers that don’t support datalist, the input box falls back to a standard text input. Please keep this in mind if you require certain input values from the user, and ensure you have contingencies in JavaScript and on the server side.