The datalist tag
The datalist
tag creates autocomplete for input
input fields in an HTML form.
The essence of autofill: when the user tries to type something in the input field, a pop-up hint will appear at the bottom, which will be a list of available options to choose from. The user will be able to select one of the suggested options without typing it all the way through.
To attach autocomplete to the input
tag, it must be given the list
attribute, in which the attribute should be specified id
binding tag datalist
.
The options are stored in option
tags, which in turn are stored in datalist
tag.
Example
Let's enter a country in the input field. First, enter the letter 'b'
- and we'll see a pop-up suggestion of three countries. Then we'll also enter the letter 'e'
- the number of suggested countries will be reduced to two:
<input type="text" list="country">
<datalist id="country">
<option>Belarus</option>
<option>Belgium</option>
<option>Bulgaria</option>
</datalist>
:
Example
Let's now add the attribute value
to the tag option
. When selecting a specific country, the bound input will not contain the country name, but the contents of the attribute value
:
<input type="text" list="country-value">
<datalist id="country-value">
<option value="Belarus">Belarus - a country of lakes and potatoes</option>
<option value="Belgium">Belgium - a country where Belgians live</option>
<option value="Bulgaria">Bulgaria - a country for vacation</option>
</datalist>
:
Example . Impact of the autocomplete attribute
The drop-down list of suggestions is affected by the attribute autocomplete
. If it is enabled (and it will be by default), the values you set in the datalist
tag will be mixed with the values the user has previously entered in this field.
Enter 'Brazil'
into the field and click the submit button (without submitting, the browser will not remember this country). Then return to this example and enter the letter 'b'
- in the list that appears, you will see not only 3
countries from datalist
, but also the country you entered earlier (in addition, if you do the same with the word 'Belarus'
- this value will be in the drop-down list twice).
If this bothers you, disable the attribute autocomplete
, adding the value off
to it.
Perform the above manipulations with the example:
<form action="">
<input type="text" list="country" autocomplete="on">
<datalist id="country">
<option>Belarus</option>
<option>Belgium</option>
<option>Bulgaria</option>
<input type="submit">
</datalist>
</form>
:
See also
-
attribute
autocomplete
,
which sets autofill for form fields