Grouping Controls
Grouping needs to be carried out visually and in the code, for example, by using the <fieldset>
and <legend>
elements to associate related form controls. Also, related entries of a <select>
element can be grouped using <optgroup>
.
Associating related controls with fieldset
The <fieldset>
element provides a container for related form controls, and the <legend>
element acts as a heading to identify the group.
The legend for a group of controls can also highlight common attributes of all controls, for example, to advise that all fields in the group are required.
Radio buttons
In the example below, there are three radio buttons that allow the user to choose an output format. Radio button groups should always be grouped using <fieldset>
.
Checkboxes
In the example below, three checkboxes are part of an opt-in function for receiving different types of information.
Related fields
This example shows form fields to enter shipping and billing addresses. As the labels in both groups have the same text, the fieldset
element also helps to distinguish the form fields by their groups. In case the <legend>
is not read by screen readers (see note below), labels for the first form control in each group should include the group’s name. This name can be hidden visually.
Note: Depending on the configuration, some screen readers read out the legend either with every form element, once, or, rarely, not at all. To accommodate this consider the following:
- Make the legend as short as possible for situations in which it is read together with the label each time.
- Make the individual labels sufficiently self-explanatory for situations in which legends are not read aloud, without repeating the legend in every label.
Associating related controls with WAI-ARIA
WAI-ARIA provides a grouping role that functions similarly to fieldset
and legend
. In this example, the div
element has role=group
to indicate that the contained elements are members of a group and the aria-labelledby
attribute references the id
for text that will serve as the label for the group.
This technique provides additional styling possibilities.
Because WAI-ARIA not fully supported in all web browser and screen reader combinations, a group identifier should be added to the first form control in the group.
Grouping items in select
elements
For select
elements with groups of options, the optgroup
element can be used to indicate such groups. The label
attribute of the optgroup
element is used to provide a label for the group. This is especially useful for lists with many related options. In the example below, users can choose from lectures in one of three courses.