jeff jeff - 13 days ago 4
HTML Question

What does "for" attribute do in HTML <label> tag?

I wonder what is the difference between these two codes:

<label for='theinput'>Input here : </label>
<input type='text' name='theinput' id='theinput'/>


and

<label>Input here : </label>
<input type='text' name='theinput' id='theinput'/>


I'm sure it does something when you use a special JavaScript library, but apart from that, does it validate the HTML or required for some other reason?

Answer

The <label> tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:

First, you can wrap the label element around the input element:

<label>Input here:
    <input type='text' name='theinput' id='theinput'>
</label>

The other way is to use the for attribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>

This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.

Read more about this element in MDN.