Wednesday, October 21, 2009

Use of "for" attribute of html label

I have noticed many of the html programmers that, they use an attribute called "for" when writing a label tag. And the attribute value is exactly same as the corresponding html input control such as text box, check box, drop down,... But I never tried to know the actual use of this attribute.

Very recently, I have searched in Google to know the use of it. Now I have come to know that, the "for" attribute of label binds the label with the corresponding control. Binding in the sense, when the user clicks on the label it toggles the corresponding control (control id passed as value for "for" attribute). This way the "for" attribute is used for the label. Now onwards I am going to make a good practice of using "for" attribute of the label control.

Let's see an example of the usage of the "for" attribute of label control

<label for="FirstName">First Name:</label>

<input id="FirstName" type="text">

The above code is rendered as shown below. You can test this behavior by clicking on the label "First Name:". You can notice the text box focused.