Yarin
Yarin

Reputation: 183519

Why are "for" attributes for form labels necessary?

Why are "for" attributes for form labels necessary? I've never had a use for them

Upvotes: 4

Views: 604

Answers (4)

Guffa
Guffa

Reputation: 700302

It will associate the label with the form field. This is especially useful for radio buttons so that you can click the label to select the button, not just the tiny button itself.

However, you don't need to use the for attribute for that, you can also put the radio button inside the label:

<label>
  <input type="radio" name="selection" value="yes" />
  Certainly
</label>

I usually put a span tag around the text also, so that it can easily be styled using CSS.

Upvotes: 2

James Montagne
James Montagne

Reputation: 78650

When used with radio buttons, it lets the click on the label select the radio button:

http://jsfiddle.net/DLL73/

notice that clicking on ONE does nothing because it's not using the for attribute, but clicking on TWO selects that radio button.

Upvotes: 3

Scott C Wilson
Scott C Wilson

Reputation: 20016

@ChristopherArmstrong's answer is technically correct - but the reason it's a good thing is that people who have trouble pointing correctly (older users, people with disabilities, etc.) are helped by this. It lets them get the cursor "about right" and still land in the right field.

Upvotes: 3

Christopher Armstrong
Christopher Armstrong

Reputation: 7953

The main advantage is that clicking on a label with a "for" attribute will auto-focus on that form element. So, a label for an input field will be associated with that input field, and clicking on the label will autofocus the input.

Upvotes: 8

Related Questions