What is the datalist tag in HTML?
The datalist tag is used to provide an auto-complete option for users through a dropdown menu. It is used together with the input tag in forms.
The datalist tag has a single attribute: an id.
The
idattribute ofdatalistmust match thelistattribute of theinputtag. This ensures that the dropdown menu is related to the input field.
The illustration below shows how thedatalist tag can be used in HTML:
Syntax
The syntax of datalist tag is as follows:
<datalist id="some-id">
<option value="A">
<option value="B">
<option value="C">
</datalist>
We begin by opening the tags using the <> symbol. In between the symbol, we write datalist. We then close the tags using </>. Once again, we will place the name of our tag in-between <> and after the / symbol.
The id acts as an identifier of the datalist tag. Each option inside the dropdown menu comes inside the option tag. The option tag is also enclosed within the <> symbol. Finally, each option has a value attribute that holds each value inside the dropdown menu.
Example
The code snippet below shows how the datalist tag can be used in HTML:
Names of all countries have not been added to the list.
Explanation
- The
labeltag places a label next to the input field. - The
inputtag creates a textbox for user input. - The
datalisttag can have as manyoptiontags as possible. Eachoptiontag has avaluethat stores a country name. - Notice that the
idattribute of thedatalisttag is the same as thelistattribute of theinputtag. - When a letter is entered inside the textbox, a dropdown menu appears holding country names for auto-fill.
Free Resources