HTML Tutorials

Adding labels to a form

You have a form that collects data from the user, but it isn’t very easy to use. You can see how the input element added in the previous section is displayed by the browser below.

The obvious problem is a complete lack of guidance for the user, who would have to read the source HTML to figure out what each of the text boxes is for. You can address this problem by using the label element, which lets you provide some context for each element in a form.

Using the label element
    <meta name="author" content="Adam Freeman"/>
    <meta name="description" content="A simple example"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    <form method="post" action="http://titan:8080/form">
      <p><label for="fave">Fruit: <input id="fave" name="fave"/></label></p>
      <p><label for="name">Name: <input id="name" name="name"/></label></p>
      <button>Submit Vote</button>

We added a label for each of the input elements. Notice that we added an id attribute to the input elements and used these ids as the value for the for attributes on the label elements. This is how you associate labels with inputs, which makes processing forms simpler for screen readers and other assistive technologies. You can see how the labels appear below:

In the code, we placed the input elements as contents of the label elements. This isn’t a requirement, and the two elements can be defined independently of one another. It is common to define the labels independently of the inputs when laying out complex forms.