Making HTML Forms More Accessible and Improving Usability with the Label Tag

It's surprising that there are still HTML forms online not taking advantage of the <label> tag. In addition to being required for creating accessible forms, <label> tags improve the usability of forms. For example, instead of forcing visitors to click those tiny radio buttons, why not let them to click the text label.

The Code

Let's say we have the following form fields:

<div>Name: <input type="text" name="name"></div>
<div><input type="radio" name="subscribe"> Yes &nbsp;
<input type="radio" name="subscribe"> No</div>

In order to add the <label> tags, we'll need to add ID attributes to the <input> tags. The attributes can be set to whatever we want, as long as every input tag has a different ID value.

<div>Name: <input type="text" name="name" id="name"></div>
<div><input type="radio" name="subscribe" id="subscribe_yes"> Yes &nbsp;
<input type="radio" name="subscribe" id="subscribe_no"> No</div>

The <label> tags then get added around the text label with the for attribute set to the corresponding <input> tag's ID attribute.

<div><label for="name">Name:</label> <input type="text" name="name" id="name"></div>
<div><input type="radio" name="subscribe" id="subscribe_yes"> <label for="subscribe_yes">Yes</label> &nbsp;
<input type="radio" name="subscribe" id="subscribe_no"> <label for="subscribe_no">No</label></div>

Making Sure the Label Works

When posting code to a website, its good practice to make sure everything works as expected. It's very easy to mistype the attribute values so they don't match or to forget some part of the code. Another common issue that may come up is when multiple form fields are given the same ID attribute.

An easy way to verify the <label> tags are functioning properly is to click the corresponding text labels. If the flashing text bar is placed in the corresponding form field, as shown in Figure 1, we're good. Likewise, radio buttons will be selected as we click their labels.

Screenshot showing the label tag in action
Figure 1. Clicking the Text Labels


With the <label> tags in place, visitors can now click the corresponding field labels to place focus on the field of interest. Plus, the form will be more accessible to those using assistive technologies such as screen readers since the label will be read aloud when focus is placed on the fields.

Related Links


There are currently no comments.

Leave a Comment