HTML <optgroup> tag is used to group related <options> in a drop down list within <select> element.
Using <optgroup> tag with <select> makes easier to access the dropdown list especially if list has large number of options.
Syntax
<optgroup label=” “>……..</optgroup>
The objective of this technique is to group items in a selection list. A selection list is a set of allowed values for a form control such as a multi-select list or a combo box. Often, selection lists have groups of related options. Those groups should be semantically identified, rather than simply delimiting the groups with “dummy” list entries. This allows user agents to collapse the options by group to support quicker skimming of the options, and to indicate in what group an option of interest is located. It also helps to visually break up long lists so that users can more easily locate the option(s) they are interested in.
In HTML, the select
element is used to create both multi-select lists and combo boxes. The various allowed options are each indicated with option
elements. To group options together, use the optgroup
element, with the related option
elements inside that element. Label the group with the “label” attribute so users will know what to expect inside the group.
The optgroup
element should be directly inside the select
element, and the option
elements directly inside the optgroup
. It is possible for a select
element to contain both single option
elements and optgroup
groups, though authors should consider if this is in fact the desired intent when using this. It is not possible to nest the optgroup
element, so only one level of grouping can be done within a select
.
If grouping information is essential to understanding the list, authors may define option
labels that can be understood even when the screen reader does not present the grouping information provided by optgroup
.
Example
The following combo box collects data about favorite foods. Grouping by type allows users to select their preference more quickly.
Example Code:
<form action="http://example.com" method="post">
<label for="food">What is your favorite food?</label>
<select id="food" name="food">
<optgroup label="Fruits">
<option value="1">Apples</option>
<option value="3">Bananas</option>
<option value="4">Peaches</option>
<option value="5"> Mango</option>
</optgroup>
<optgroup label="Vegetables">
<option value="2">Carrots</option>
<option value="6">Cucumbers</option>
<option value="7"> Lettuce</option>
</optgroup>
<optgroup label="Baked Goods">
<option value="8">Apple Pie</option>
<option value="9">Chocolate Cake</option>
</optgroup>
</select>
</form>
The Output of the above code is shown below: