Reference · Beginner
The datalist element
datalist attaches native autocomplete suggestions to a text input, giving users options without restricting them to a fixed list.
- Published
- Last checked
What it is
datalist holds a set of option elements that a browser offers as
autocomplete suggestions for a text input. The input opts in by pointing its
list attribute at the datalist's id:
<label for="city">Nearest city</label>
<input id="city" name="city" list="city-options" />
<datalist id="city-options">
<option value="Austin"></option>
<option value="Boston"></option>
<option value="Chicago"></option>
</datalist>
The user can pick a suggestion or type anything else. That is the defining property: suggestions, not constraints.
Datalist or select
The two answer different questions. A select restricts the answer to the
options you provide; a datalist accelerates typing while leaving the answer
open. Choose by asking whether an answer outside your list is valid. Country
pickers and status fields want select. A "how did you hear about us" field or
a search box with common queries wants datalist, because forcing an unexpected
answer into a fixed list produces wrong data rather than better data.
If the value must come from the list, a datalist alone is the wrong tool: it
does not validate. Pair it with server-side checking or use a select.
Native behavior
The browser renders the suggestion popup, filters options as the user types, and handles keyboard and touch interaction with no script. The datalist itself is not rendered. Filtering behavior and popup appearance differ between browsers, and you cannot style the popup; if a design requires styled suggestions, you are building a custom combobox and taking on its full keyboard and ARIA contract, which is a substantially larger job than it looks.
The list attribute also works with several non-text input types, but support
varies; test the exact combination before relying on it.
Accessibility
The native pairing avoids rebuilding the full ARIA combobox contract, but
announcement and keyboard behavior can still vary by browser and assistive
technology. Test the combinations your audience uses. The ordinary requirements
remain: the input still needs its label, and each option's value should be
the literal text you want submitted, since assistive technology reads the value
itself.
Common failures
- A
listattribute that does not match anyid, so suggestions silently never appear. - Treating the suggestions as validation and being surprised by free-text submissions.
- Replacing a required fixed choice with a datalist, letting typos into data that needed to be clean.
- Rebuilding the popup in script to style it, and losing the keyboard and announcement behavior the native version provided.
Verify it
Type into the field and confirm suggestions appear and filter. Choose one with the keyboard alone. Then submit a value that is not in the list and check the server handles it, because it will arrive.