HTML Forms – Identifying inputs
Label
The <label>
element is the most formal way to tie an input to it’s label. This is the most important element when building accessible forms. When you implement it correctly, screen readers and other software will speak aloud the element’s label along with any other related instructions.
This is how we use it:
<label for="name">Name:</label> <input type="text" id="name" name="user_name">
You associate the label to the input via the for
and id
attributes.
This will get the screen reader to read something like “Name. Edit text”
Another bonus of setting a label to tie to it’s input, is when you use a checkbox or radio, it will actually make the label click-able and correctly check or uncheck the box.
<div>
<input type="checkbox" id="coding" name="interest" value="coding" checked>
<label for="coding" style="display: inline-block">Coding</label>
</div>
<div>
<input type="checkbox" id="music" name="interest" value="music">
<label for="music" style="display: inline-block">Music</label>
</div>
Fieldsets and legends
The <fieldset>
element can be used to group inputs together, semantically and/or with styles. You can add a label to a fieldset by using the <legend>
tag. The legend is used to formally describe the fieldset that it is inside.
Assistive software like screen readers will read the legend of a fieldset with each input.
<form>
<fieldset>
<legend>Fruit juice size</legend>
<p>
<input type="radio" name="size" id="size_1" value="small">
<label for="size_1">Small</label>
</p>
<p>
<input type="radio" name="size" id="size_2" value="medium">
<label for="size_2">Medium</label>
</p>
<p>
<input type="radio" name="size" id="size_3" value="large">
<label for="size_3">Large</label>
</p>
</fieldset>
</form>
The screen reader, for the above code, would speak something like “Fruit juice size small” for the first input, and “Fruit juice size medium” for the second and so on.
This use case is one of the most important when considering accessibility. You should nest each radio group inside of a fieldset
.
It can also be used to break up forms into sections. But make sure that it makes sense. It sometimes is better to break up the form across multiple pages rather than sectioning off a single page.
Listen to it on screen reader software and make sure that it makes sense and isn’t too complicated to understand.