The <datalist>
element contains a set of <option>
elements representing predefined options for other input elements. You can use it with the <input>
element, whose list
attribute references the <datalist>
element.
It’s a great way of giving users options for form data entry, whilst giving them the alternative of free text entry, unlike the more restrictive <select>
element.
Syntax
1 | <datalist> |
2 | <optionvalue="option1"> |
3 | <optionvalue="option2"> |
4 | <optionvalue="option3"> |
5 | </datalist> |
Example
Here’s an example using fruits as options for a form input. Note the <input>
element’s list
attribute which references the datalist:
Syntax
1 | <labelfor="fruits">Choose a fruit:</label> |
2 | <inputlist="fruit-options"name="fruits"id="fruits-input"placeholder="Fruit options"> |
3 | |
4 | <datalistid="fruit-options"> |
5 | <optionvalue="Apple"> |
6 | <optionvalue="Banana"> |
7 | <optionvalue="Cherry"> |
8 | <optionvalue="Durian"> |
9 | <optionvalue="Elderberry"> |
10 | <optionvalue="Fig"> |
11 | <optionvalue="Grape"> |
12 | <optionvalue="Honeydew"> |
13 | </datalist> |
Result
Users can enter any text they like, click on a suggested option from the datalist, or enjoy the fruits of autocomplete:
Attributes
Attribute | Description |
id | Specifies a unique id for the element. |
class | Specifies a class name for the element. |
name | Specifies the name of the list of options. |
value | Specifies the value of an option |
label | Specifies a label for an option |
Content
The <datalist>
element contains only <option>
elements which represent a single item within the “list”.
Did You Know?
- The
<datalist>
element was introduced in HTML5 to provide autocomplete options for text inputs. - Multiple input elements on the same page can use the
<option>
elements inside a single<datalist>
element. - When a user types in an
<input>
element with a list attribute that references a<datalist>
element, the browser will show a dropdown list of options from the<datalist>
element that matches the text entered so far.
Learn More
- To learn more about the
<datalist>
element, you can check out the official HTML specification.