The datalist element
Published on
The <datalist>
element is one of those HTML features that doesnât get nearly enough attention, but itâs incredibly useful for creating autocomplete suggestions on text inputs without any need for JavaScript.
It works by providing a list of predefined options that users can choose from.
Users are still free to type in their own values, but it can be a helpful way to provide some suggestions for popular answers.
Hereâs how you use it:
<label for="browsers">Choose your browser:</label>
<input list="browser-list" name="browsers" id="browsers" />
<datalist id="browser-list">
<option value="Chrome"></option>
<option value="Firefox"></option>
<option value="Safari"></option>
<option value="Edge"></option>
</datalist>
Which will givey you an input like this:
For it to work, you connect the input to the datalist using the list
attribute on the input, so that it matches the id
on the datalist.
Itâll be a little different in each browser, butf when users start typing, theyâll see suggestions that match what theyâve entered. They can either select from the suggestions or type something completely different.
Itâs not just for text inputs!
For example, you can use it for a color input as well!
It also works with ranges, dates, and more.
This doesnât replace <select>
A <select>
limits what the user can select from a predefined list of choices, while a datalist is simply a list of suggestions, but a user is still free to write anything they want.