HTML <datalist>
Tag
The <datalist>
tag in HTML is used to provide a pre-defined list of options for <input>
elements. This allows users to input data by choosing from a list of options, rather than typing it out manually. The options in the datalist can be suggested as the user types in the input field, making it a useful feature for forms and search functions.
How to Use the <datalist>
Tag
To use the <datalist>
tag, you need to follow these steps:
- Create an input field with the
<input>
tag. - Add a
list
attribute to the<input>
tag and set it to the ID of the<datalist>
element. - Create a
<datalist>
element with an ID that matches thelist
attribute in the<input>
element. - Add
<option>
elements inside the<datalist>
element to provide the list of options.
Main Attributes of the <datalist>
Tag
Attribute | Description |
---|---|
id |
Sets the ID of the <datalist> element, which is used to link it to an <input> element. |
Example: Using the <datalist>
Tag
Let's create an example where we have an input field for selecting a country from a list of options:
<input type="text" list="countries">
<datalist id="countries">
<option value="USA">
<option value="Canada">
<option value="UK">
<option value="Australia">
</datalist>
In this example, as the user types in the input field, a list of country options will be suggested based on the <datalist>
element.