views:

64

answers:

3

Considering the following 2 lines of code (copied from w3schools.com > "HTML < label > for Attribute"):

  <label for="male">Male </label>
  <input type="radio" name="sex" id="male" />

I am having trouble discovering the exact purpose of the above label's "for" property. As you can see it is currently set to "male" (to match the id of the input control).

All I have read so far is that the above code will 'associate' and 'bound' the label with the input control. So my question is, what exactly does this mean?

What exactly are the results of associating the label to the input control?
Does the label and/or input have new behaviours as a result of this 'association'?

Thankyou for any information,
Gadmeer.

+6  A: 

A label that is associated with a control via for will be clickable. Clicking it selects the control. Highly useful with radio/checkboxes in particular. It also has accessibility implications for screen readers for the visually impaired.

ceejayoz
+1 you click the text and the bound <input> element will be selected
galambalazs
A: 

When you click on the label (Male), the radio will be checked something not possible if you are not using a lable. A lable is also useful when developing for small devices such as mobiles.

So, it is useful for:

  • accessibility reasons
  • smaller devices such as mobiles, etc
  • useful in radio buttons and check boxes especially

Resources:

Dive Into Accessibility: Labeling form elements

Sarfraz
Uh, it's `label`, not `lable`.
ceejayoz
@ceejayoz: yes a typo, fixed, thanks
Sarfraz
A: 

I believe that linking a label to a form element allows you to assign the label an access key, which will bring the focus to the form element associated with it.

As others have mentioned it also allows you to click on the label and bring focus to the form element.

The for attribute alllows you to place the label and the element in semantically different areas of the html, and maintain association. (Like two tables, or two different divs). If you're putting both of them together like in your example, it is also correct to enclose the form element in the label and forgo the for attribute

Alex Larzelere