The 'optgroup' Tag
The optgroup
tag is available to use when a dropdown list has more than one category of items. The category name is printed above the items of that category.
This example illustrates a use of the optgroup
tag for a dropdown of types of birds.
The optgroup
tag is used to visually separate the items of each category. Note that the categories themselves are not selectable, only the actual options.
Here is the source code for the above example.
<select name="birds" id="birds"> <option>Select a Bird</option> <optgroup label="North American Birds"> <option value="greathornedowl">Great Horned Owl</option> <option value="cardinal">Cardinal</option> <option value="killdeer">Killdeer</option> <option value="sandpiper">Sandpiper</option> </optgroup> <optgroup label="Tropical Birds"> <option value="macaw">Macaw</option> <option value="toucan">Toucan</option> <option value="parrot">Parrot</option> <option value="cockatoo">Cockatoo</option> </optgroup> </select>
For ease of identification, the opening and closing optgroup
tags are colored blue in the above code. The label
attribute, which prints the category name above the category list, is colored red.
The optgroup
tag needs the label
attribute so the browser knows what to print for the category name. Without a label
attribute, the browser might print a blank line or it might do something different; I was unable to find an authoritive statement about that. (All of my browsers print a blank line.)
When you have two or more categories of options for a dropdown list, and you wish to separate them out for the user, the optgroup
tag can be used.
(This content first appeared in Possibilities newsletter.)
Will Bontrager