HTML and CSS Reference
In-Depth Information
Suggesting Options with Data Lists
The last data field that Alice wants added to the survey form is a text box in which cus-
tomers can indicate their favorite Red Ball Pizza dish. There are a lot of possible answers
and Alice doesn't want to limit the options to a selection list, but she does want to pro-
vide suggestions to customers as they type their entries. For example, as the user types
a
B
, Alice would like the text box to display entries such as
Big Kahuna Pizza
or
BBQ
Chicken Pizza
(both of which are Red Ball Pizza specials that start with
B
).
You can create this effect using the HTML5
datalist
element
<datalist id=”
id
”>
<option value=”
value
” />
<option value=”
value
” />
…
</datalist>
where
id
is the id of the list and the values assigned to the different
option
elements
provide the suggested entries in the list. To apply a
datalist
to a text input box, add the
list
attribute to the
input
element as follows
<input name=”
name
” list=”
id
” />
where
id
references the id of the data list. For example, to create an input box for
the
favDish
field that offers a few suggested items, you could enter the following
HTML5 code:
<input name=”favDish” list=”dishes” />
<datalist id=”dishes”>
<option value=”Antipasto Pizza” />
<option value=”Big Kahuna Pizza” />
<option value=”BBQ Chicken Pizza” />
</datalist>
The options in the
dishes
data list are just suggestions. The customer is not obligated
to accept any options and can type a dish of his or her own choosing. Currently, the
list
attribute and the
datalist
element are supported only by the Firefox and Opera
browsers. Other browsers that encounter this code ignore both the attribute and the ele-
ment, and treat the input box as just another text box.
Creating and Applying a Data List
• To create a data list of possible values, enter the HTML code
<datalist id=”
id
”>
<option value=”
value
” />
<option value=”
value
” />
…
</datalist>
where the
value
attribute provides the text of the possible values in the data list.
• To reference the data list from an input control, add the
list
attribute
<input name=”
name
” list=”
id
” />
where
id
references the id of the data list structure.