<datalist> Autocomplete
Overview
Sometimes a Select dropdown restricts users too much, but a standard text input gives them too much freedom. The <datalist> tag provides the ultimate hybrid: it acts as a standard, type-able text input, but provides a smart, auto-filtering dropdown menu of suggested options. It provides massive UX benefits without requiring a single line of JavaScript or importing complex third-party autocomplete libraries.
Syntax
<!-- The standard text input must have a 'list' attribute -->
<label for="browser">Choose your favorite browser:</label>
<input list="browsers_list" id="browser" name="browser" placeholder="Type or select...">
<!-- The datalist provides the suggestions, linked by the 'id' -->
<datalist id="browsers_list">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
<option value="Brave">
</datalist>Common Pitfalls
- Assuming
<datalist>restricts the user's input. It does NOT. It only provides suggestions. The user is perfectly free to ignore the dropdown entirely and type 'Internet Explorer 6'. If you need strict enforcement, you must validate on the backend or use a<select>tag. - Applying CSS directly to the
<datalist>or<option>tags. Browsers severely lock down the styling of native datalists. You cannot easily change the dropdown background color or hover states via CSS.
Interview Questions
<select> tag and an <input> powered by a <datalist>?A <select> is a closed system; the user can ONLY choose one of the predefined options. A <datalist> is an open system; it acts as a suggestion engine, but ultimately allows the user to submit any custom text they want.
Real-World Example
An elegant country selection field that lets users type to instantly filter 200+ countries.
<!--
As the user types "Uni", the datalist will instantly filter
and show "United States" and "United Kingdom".
-->
<label for="country">Country:</label>
<input list="countries" id="country" name="country">
<datalist id="countries">
<option value="United States">
<option value="United Kingdom">
<option value="Canada">
<option value="Australia">
<!-- 190 more options... -->
</datalist>Check Your Knowledge
Test your understanding of <datalist> Autocomplete with these quick questions.