Datalist and output
Learn <datalist> and <output>.
Ready suggestions with datalist
Sometimes you want to offer ready suggestions for a field: city, category, language. <datalist> is for that. You place <option value="..."> tags inside it; the browser shows these suggestions in a drop-down as the user types.
The key part: the input's list attribute must point to the datalist's id. The user can still type something else; datalist suggests, it does not force.
Calculation results with output
To show the result of a calculation on the page you use the <output> tag. Its value is changed by JavaScript; HTML alone does not compute.
The output's for attribute lists the ids of the inputs used in the calculation, separated by spaces. This tells the screen reader which fields feed the result and helps accessibility. The user then sees the result tied to its sources.
Exercise Write a city suggestion box
Add an <input type="text"> to the form; give it name of sehir and set list to sehirler. Then add a <datalist id="sehirler"> with at least two <option value="..."> inside (values do not matter). Close the datalist with its closing tag.
Show example solution
<form>
<input type="text" name="sehir" list="sehirler">
<datalist id="sehirler">
<option value="London"></option>
<option value="Paris"></option>
</datalist>
</form>
Test yourself
-
Which statement is correct?
- datalist restricts the user's choice
- the output tag collects text from the user
- output shows a calculation result on the page
- the list attribute links to output
Show answer
output shows a calculation result on the page — Correct. output shows the calculation result on the page; JavaScript updates its value.
-
What should the id of a datalist with two city suggestions be?
<datalist id="____"> <option value="Istanbul"></option> <option value="Ankara"></option> </datalist>Show answer
<datalist id="cities"> <option value="Istanbul"></option> <option value="Ankara"></option> </datalist> -
Match each tag and attribute to its role
- datalist
- Offers suggestion list
- output
- Shows calculation result
- list
- Links input to datalist
- value
- Value of an option