8.7. Creating Complex Select Menus with optgroup
Problem
You want to group related choices logically on a form.
Solution
Use the <optgroup>
element to create groups of similar options within one select
menu.
<select name="name
"> <optgroup label="label
"> <option label="label
"value="value
">label
</option> <option label="label
" value="value
">label
</option> </optgroup> </select>
Discussion
In a simple select menu, the options are listed together within
the <select>
element. Adding
the <optgroup>
element offers
a way for you to group sub-lists of options hierarchically so the menu
choices appear more clearly to the user. There's no limit to the
number of <options>
that can
be listed within an <optgroup>
, and no limit to the number
of <optgroups>
that can be
included in one list.
You also can display one or many options on the page (using the
size
attribute) and allow the user
to select more than one option by adding the multiple
attribute to the <select>
element (see Figures 8-6 and 8-7).
Figure 8-6. The <optgroup> values in this select menu (Small, Medium, etc.) are not selectable themselves, but serve to organize the <option> values indented and listed beneath them
Figure 8-7. Adding the size attribute to a select menu with five <optgroup> elements causes the entire menu to be displayed ...
Get Web Site Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.