Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use the "for" keyword to bind a label in HTML? [duplicate]

Tags:

html

Possible Duplicate:
What is the For attribute for in an HTML tag?

I have been trying to find this out. What is the reason for using the "for=" when you use a label in HTML?

<form>   <label for="male">Male</label>   <input type="radio" name="sex" id="male" />   <br />   <label for="female">Female</label>   <input type="radio" name="sex" id="female" /> </form> 

If it's needed then is there some equivalent in HTML 5 or is it the same?

like image 595
Alan2 Avatar asked May 30 '12 09:05

Alan2


People also ask

What is the use of for in label in HTML?

The HTML <label> for Attribute is used to specify the type of form element a label is bound to. Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to. Example: This Example that illustrates the use of for attribute in <label> element.

What is the for attribute in label?

The for attribute is an allowed attribute for <label> and <output> . When used on a <label> element it indicates the form element that this label describes. When used on an <output> element it allows for an explicit relationship between the elements that represent values which are used in the output.

Why should the value of the for attribute of label tag be same as the ID of the corresponding input element?

A label is attached to a specific form control through the use of the for attribute. The value of the for attribute must be the same as the value of the id attribute of the form control. The id attribute may have the same value as the name attribute, but both must be provided, and the id must be unique in the Web page.

How do you bind input and label in HTML?

Tip: The for attribute of <label> must be equal to the id attribute of the related element to bind them together. A label can also be bound to an element by placing the element inside the <label> element.


1 Answers

It makes a click on the label focus the input element it is for.

In the example you posted, you simply click on the word Male or the radio button in order for it to get selected. Without this, you have a much smaller target to click...

If it's needed then is there some equivalent in HTML 5 or is it the same?

It is not required, but is good practice for labels that have a direct form element to focus on (it wouldn't make much sense for a label that doesn't have a counterpart on a form).

The syntax is the same for HTML 5.

like image 152
Oded Avatar answered Sep 30 '22 19:09

Oded