HTML and CSS

Making Forms More Accessible with label

By their very interactive nature, forms are a bit more demanding in the accessibility department than other HTML elements. This is largely because all the items we've been discussing in this tutorial have to do with form controls, which are components built into browsers and invoked by the corresponding HTML.

For a visual person, all this makes sense. But for individuals who are having the form read to them instead of seeing it, context can be quickly lost.

The label element allows information to be attached to a given control. Using this along with the for attribute enables you to describe the form control being used in more detail (see Example 5-13).

Example 5-13. Adding context using the label element
<form method="get" action="http://www.myserver.com/cgi-bin/mailscript/">

<label for="firstname">First Name:</label><input type="text" name="firstname"
 id="firstname" /><br />
<label for="reading"><input type="checkbox" name="reading" id="reading" />Reading<br />

<label for="requestbox">Any special requests?</label> <br> <textarea name="comments"
 id="requestbox" cols="25" rows="5">
</textarea>

</form>

You'll recall that earlier I mentioned that the use of the id attribute within the input was an important part of accessibility, and here you see why.

NOTE

You'll notice that the label always comes before the control it's describing. In every case in which you are labeling a form control, the value of the for attribute must match the exact value of the id attribute within the control itself. This enables screen readers to provide more descriptive information about the control.

Another important issue is that labels do not need to be applied to submit and reset buttons. This is because screen readers read the text you've supplied on the buttons, automatically providing the required context.