Simplify Your HTML Labels
<< February | March | April >>
Wednesday, 30th March 2011
The HTML label element is a really useful way of linking descriptive text to a form element on your web page. It semantically attaches the text to the input field and makes forms much easier to use for impaired users.
There are two ways of linking the label to the form element and I'm not sure people know about both methods as I am seeing a lot of long-hand usage where it isn't required.
So to start with, here is a form without labels.
<form method="post" action="">
<p>First name<br>
<input type="text" name="firstName"></p>
<p>Last name<br>
<input type="text" name="lastName"></p>
<p><input type="submit" value="Save"></p>
</form>
In this form, there is nothing to link the text "First Name" with the field named "firstName". The link is currently visual - the text appears very close to the box. This link is even more detached when different elements are used to lay out the form.
To make this implicit label explicit, we just need to use the label element, like this:
<form method="post" action="">
<p><label>First name<br>
<input type="text" name="firstName"></label></p>
<p><label>Last name<br>
<input type="text" name="lastName"></label></p>
<p><input type="submit" value="Save"></p>
</form>
We have now wrapped the text and the input element within a label tag, which now explicitly links the two together. If the focus is switched to the form field with a screen-reader active, the screen-reader can now read out the text "First Name", because the label associates this text with the form field.
This is the short-hand way of associating the text with the form field. Sometimes you can't do it this way, because the text and the field aren't enclosed within the same block element - a good example of this is where some people use a table to lay out the form (I won't discuss whether tables are the correct element for this job in this article!)
To make it possible to link the label and form field, even when they are located in different places, you can use the form field id to match them, like this:
<form method="post" action="">
<table>
<tr>
<td><label for="firstName">First name</label></td>
<td><input type="text" name="firstName" id="firstName"></label></td>
</tr>
<tr>
<td><label for="lastName">Last name</label></td>
<td><input type="text" name="lastName" id="lastName"></label></td>
</tr>
</table>
<p><input type="submit" value="Save"></p>
</form>
The "for" attribute allows the label to be linked to the input using the "id" attribute of the input. This is fine to use when you can't enclose both elements in the same label element.
Where possible, you should use the short-hand version, beacuse it is more concise, easier to maintain and doesn't force you to add unnecessary attributes to the label and input elements.