Home / Using the tag for HTML forms

Using the

The <label> tag is useful in HTML forms and is an often overlooked (or not known at all) tag in the HTML coder’s arsenal. I know that I often overlook it myself. This post looks at how it is especially useful with checkboxes and radio buttons.

The <label> tag works like this:

<label for="id">Text here</label>

where "id" is the form field’s id and "text here" is some text to describe the field. When used with a checkbox or radio button, clicking the label will toggle the checked status of the box or radio button and for other input types will select them. The great thing about using this for radio buttons and checkboxes is it makes your web forms work more like a regular application where checking the text next to the option checks the box.

The easiest way to show how this works is with examples.

Radio button example

Example HTML:

<input type="radio" name="example_radio_1" id="example_radio_1a" />
<label for="example_radio_1a">This is the first option</label>
<br />
<input type="radio" name="example_radio_1" id="example_radio_1b" />
<label for="example_radio_1b">This is the second option</label>
<br />
<input type="radio" name="example_radio_1" id="example_radio_1c" />
<label for="example_radio_1c">This is the third option</label>

Working example (click the text next to the radio button to see it working):

Checkbox example

Example HTML:

<input type="checkbox" name="example_checkbox_1" id="example_checkbox_1" />
<label for="example_checkbox_1">This is the first checkbox</label>
<br />
<input type="checkbox" name="example_checkbox_2" id="example_checkbox_2" />
<label for="example_checkbox_2">This is the second checkbox</label>
<br />
<input type="checkbox" name="example_checkbox_3" id="example_checkbox_3" />
<label for="example_checkbox_3">This is the third checkbox</label>

Working example (click the text next to the check box to see it working):

Text input example

Using <label>s probably isn’t quite as useful for text boxes and input types other than radio buttons and checkboxes but they can still be used. When clicking the label text the input becomes selected.

Example HTML:

<label for="example_text_1">Text field:</label>
<input type="text" name="example_text_1" id="example_text_1" />

Working example:

Select box example

The final example is a select box and as with a regular text input the select box will have the focus set on it when the label is clicked.

Example HTML:

<label for="example_select_1">Select field:</label>
<select name="example_select_1" id="example_select_1">

Working example: