What is it for?
W3C states quite clearly that:
The
<label> element may be used to attach information to controls. Each <label> element is associated with exactly one form control.
The
for attribute associates a label with another control explicitly: the value of the for attribute must be the same as the value of the id attribute of the associated control element. More than one <label> may be associated with the same control by creating multiple references via the for attribute.
Few interesting points from the above quote for developers to understand are:
<label>may be used which implies that strictly speaking it is not needed, although I will strongly argue that not using<label>with form elements would be very bad practice- One
<label>can only label one form control, so it is impossible to use one<label>to label many form controls - Developers can use more than one
<label>in order to label any given form control, which is potentially a very powerful construct
Appropriate uses
Generally speaking the most common scenario when using <label> element is the following type of association:
<label for="username">Username or email</label>
<input type="text" name="username" id="username" />
Each form field should have a label associated with it in order to achieve proper accessibility and usability.
Inappropriate use
Not using labels with form fields
From Google
<div class="section_error">
<input type="checkbox" onclick="GWO_updateContinueButton(this)" value="yes" name="ubac_accept"/>
<strong>Yes,</strong> I accept the above Terms and Conditions.
</div>
In the above code snippet Google exemplifies some of the worst practices in User Interface development.
Apart from using non-semantic class name of ’section_error’ for a non-error content snippet, they are writing in-line JavaScript, which is harder to maintain and does not achieve separation of concerns.
Most importantly Google are not using any labels for the check box, hence they are damaging accessibility and usability of the code snippet as there is no explicit label associated with the check box to denote what the check box is for.
Considering that this code snippet finds itself in context of a very simple documentation page, there are no excuses why Google’s engineers should ever produce this bad quality of User Interface code.
A re-worked, appropriate, semantic solution for this code snippet would read something along these lines:
<div id="termsAndConditions">
<input type="checkbox" value="y" name="termsOptIn" id="termsOptIn" />
<label for="termsOptIn"><strong>Yes,</strong> I accept the above Terms and Conditions.</label>
</div>
If really required, JavaScript functionality associated with this snippet should be situated in an external JavaScript file which associates the functionality by hooking onto to the termsAndConditions ID attribute.
Written by Jason Grant, BSc, MSc on 15th June 2009