Quantcast
Channel: Envato Tuts+ Web Design
Viewing all articles
Browse latest Browse all 4338

HTML Element: datalist

$
0
0

The <datalist> element contains a set of <option> elements representing predefined options for other input elements. You can use it with the <input> element, whose list attribute references the <datalist> element.

It’s a great way of giving users options for form data entry, whilst giving them the alternative of free text entry, unlike the more restrictive <select> element.

Syntax

1
<datalist>
2
<optionvalue="option1">
3
<optionvalue="option2">
4
<optionvalue="option3">
5
</datalist>

Example

Here’s an example using fruits as options for a form input. Note the <input> element’s list attribute which references the datalist:

Syntax

1
<labelfor="fruits">Choose a fruit:</label>
2
<inputlist="fruit-options"name="fruits"id="fruits-input"placeholder="Fruit options">
3
4
<datalistid="fruit-options">
5
<optionvalue="Apple">
6
<optionvalue="Banana">
7
<optionvalue="Cherry">
8
<optionvalue="Durian">
9
<optionvalue="Elderberry">
10
<optionvalue="Fig">
11
<optionvalue="Grape">
12
<optionvalue="Honeydew">
13
</datalist>

Result

Users can enter any text they like, click on a suggested option from the datalist, or enjoy the fruits of autocomplete:

Attributes

AttributeDescription
idSpecifies a unique id for the element.
classSpecifies a class name for the element.
nameSpecifies the name of the list of options.
valueSpecifies the value of an option
labelSpecifies a label for an option

Content

The <datalist> element contains only <option> elements which represent a single item within the “list”.

Did You Know?

  • The <datalist> element was introduced in HTML5 to provide autocomplete options for text inputs.
  • Multiple input elements on the same page can use the <option> elements inside a single <datalist> element.
  • When a user types in an <input> element with a list attribute that references a <datalist> element, the browser will show a dropdown list of options from the <datalist> element that matches the text entered so far.

Learn More


Viewing all articles
Browse latest Browse all 4338

Trending Articles