Sub topic 2
Grouping Related Fields with `fieldset` and `legend`
Assume basic HTML, CSS, and JavaScript. This chapter focuses on making related controls understandable to sighted and screen reader users.
Grouping Related Fields with `fieldset` and `legend`
Use <fieldset> when several controls answer one shared question. Use <legend> for that question. A separate label on each radio button identifies the option, but not the group.
<form>
<fieldset>
<legend>Preferred contact method</legend>
<label>
<input type="radio" name="contact" value="email" required>
Email
</label>
<label>
<input type="radio" name="contact" value="phone">
Phone
</label>
</fieldset>
<button type="submit">Continue</button>
</form>The shared name makes these radio buttons one choice. The browser applies required to the group: the user must select one option.
Marking Required and Optional Fields
Mark required fields with the HTML required attribute and visible text such as “Required.” Do not rely only on an asterisk. If most fields are required, label the exceptions as “Optional.” This reduces repeated visual noise.
Input Types and Autocomplete
Choose the input type that matches the data. email, tel, date, and number can provide suitable keyboards and browser validation. Add an autocomplete token so browsers and password managers can offer known values.
<label for="email">Email address</label>
<input id="email" name="email" type="email"
autocomplete="email" required>Do not choose number for values that are identifiers, such as postcodes, account numbers, or telephone numbers. These values may contain spaces, leading zeroes, or letters.
When to Validate
Validate on submit as a minimum. Validate on blur when a user has completed a field and early feedback is useful. Avoid showing errors on every keystroke unless the rule is easy to understand and the feedback will not interrupt typing.
A useful sequence is:
- Validate the group when the form is submitted.
- Validate an individual field after it loses focus.
- Show a specific message that explains the fix.
- Preserve all valid input when another field fails.
Exercise
Why is a fieldset with a legend better than placing a heading above radio buttons?
Show answer
The legend programmatically gives the radio-button group its shared question, so assistive technology can announce that context with each option.