Bookmark and Share

Optgroup element to group select options

Sometimes it is useful to group the options of an HTML select element. Many developers use extra option elements and non-breaking spaces to create the visual appearance of hierarchical options, but there is another way: the often forgotten optgroup element.

To create a group of options, wrap them in an optgroup element. To give the group a label, use the label attribute. Here is a simple example:

<label for="phones">Select a phone:</label>
<select id="phones" name="phones">
	<option selected="selected">None</option>
	<optgroup label="Apple">
		<option value="iphone">iPhone</option>
	</optgroup>
	<optgroup label="Nokia">
		<option value="n91">N91</option>
		<option value="e60">E60</option>
		<option value="6300">6300</option>
	</optgroup>
</select>

And here is how the browser you are currently using will render the above example:

One caveat is that assistive technology support for the optgroup element and the label attribute is inconsistent, as noted in Creating Accessible Forms at WebAIM and the WCAG 2 technique H85: Using OPTGROUP to group OPTION elements inside a SELECT.

Leave a Reply