HTML <datalist>
Tag
Concept
The <datalist>
tag in HTML is used to provide a predefined set of options for an <input>
element. It allows users to select from a list of suggestions as they type, enhancing the user experience in form filling. The <datalist>
tag is connected to the <input>
element via the list
attribute, and the options are defined using the <option>
tags within the <datalist>
.
Implementation
Example 1: Selecting a Fruit from a List
Here’s an example of how you can use the <datalist>
tag to create a dropdown list of fruits for the user to select:
<label for="fruits">Choose a fruit:</label>
<input list="fruits" name="fruit" id="fruit">
<datalist id="fruits">
<option value="Apple">
<option value="Banana">
<option value="Cherry">
</datalist>
Example 2: Selecting a Country from a List
You can also use the <datalist>
tag to create a dropdown list of countries:
<label for="countries">Choose a country:</label>
<input list="countries" name="country" id="country">
<datalist id="countries">
<option value="United States">
<option value="United Kingdom">
<option value="Canada">
</datalist>
powered by Advanced iFrame. Get the Pro version on CodeCanyon.
Attributes
Global Attributes
The <datalist>
tag supports all the global attributes in HTML.
Event Attributes
The <datalist>
tag also supports all the event attributes in HTML.
Browser Support
Browser | Support |
---|---|
Chrome | 20.0 |
Firefox | 10.0 |
Safari | 4.0 |
Opera | 12.1 |
IE | 9.5 |
Default CSS Settings
Most browsers will display the <datalist>
element with the following default CSS settings:
datalist {
display: none;
}
Conclusion
The <datalist>
tag is a powerful tool for enhancing user experience in form filling.
By providing a predefined set of options, it guides the user’s input and helps prevent errors. It’s particularly useful in scenarios where the input needs to be restricted to a specific set of values, such as selecting a country or a product from a catalog.