Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP
by Steven M. Schafer
9.18. Field Labels
The label tag (<label>) is used to define text labels for fields. This tag has the following format:
<label for="id_of_related_tag">text_label</label>
For example, the following code defines a label for a text box:
<p><label for="FirstName">First Name: </label> <input type="text" name="FirstName" id="FirstName" value="" size="30" maxlength="40"></p>
The label field's for attribute should match the id of the field for which it is intended. The main purpose of the label tag is accessibility—most users will be able to ascertain the purpose of fields in your forms by sight. However, if the user agent does not have a visual component, or if the user is visually impaired, the visual layout of the form cannot be relied on to match labels and fields. Note that if the user agent supports it, the user can also click on the field label to select the appropriate field.
The <label> tag's for attribute ensures that the user agent can adequately match labels with fields for the user, if necessary.
Notice the use of both the id and name attributes in the text input field tag. HTML requires a field to have a name tag for its data to be submitted. However, the label tag requires an id value in its matching input field.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access