453

I wonder what is the difference between the following two code snippets:

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

and

<label for='theinput'>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?

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
jeff
  • 13,055
  • 29
  • 78
  • 136
  • Related post - [Is “for” attribute necessary in HTML label if the target input is nested inside the label?](https://stackoverflow.com/q/8726788/465053) – RBT May 22 '21 at 05:17

7 Answers7

727

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:

One way is to 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 the <label> element on MDN.

Associating text with an input is very important for accessibility, as it provides an accessible name for the input, so that assistive technology can provide it to users with disabilities. A screen reader would read the label text when the user focusses the input. You could also tell your voice command software to focus that input, but it needs a (visible) name for that.

Read more on Accessibility

Andy
  • 4,783
  • 2
  • 26
  • 51
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 138
    Note that the for attribute is bound to the input by the id attribute, and the name attribute does not have to match. Will still work – Glo Jan 15 '15 at 14:35
  • 5
    A click on the label is not always treated exactly like clicking on the associated element. In Chrome and Safari, for example, clicking a label that is associated with a `select` only puts focus on the select rather than expanding the options. – Emile Pels Feb 08 '16 at 13:30
  • 2
    @EmilePels As far as the browser's event model is concerned, they're equivalent. What you're describing is more about the UI provided by the OS's handling of drop-down menus, which is tied to the mouse itself. – Barmar Feb 08 '16 at 15:06
  • 6
    It seems important to mention that it's very relevant for accessibility and screen readers, why actively use it. – coyotte508 Jun 06 '16 at 02:15
  • 1
    I was struggling the last two hours with the click of the body raised twice each time I click on a label in a form with the "for" attribute to an input field. I finally understand why even if I use stopPropagation on the click of the label why the click of the body was still raised... because of the click raised by the input field following the behavior that you described. – Samuel Mar 08 '17 at 16:25
  • @Barmar, could you explain a bit further what you mean? I was sure OS has nothing to do with browser inputs. The inputs are different on Firefox and Chrome and the same for Chrome on Linux and Windows. Where do you get this info? And what does the mouse have to do with it? – Gherman Oct 02 '17 at 08:06
  • I'm not sure what part of my answer you're questioning. I never said anything about the OS. But if you want to learn more details, follow the MDN link I provided, and it will have links to the relevant standards document for the official description in excruciating detail (although its language can be somewhat inscrutible). – Barmar Oct 02 '17 at 15:05
  • 1
    I hate when `for` isn't used properly, and I need to click the tiny, tiny checkbox like some kind of neurosurgeon. – Gershom Maes Aug 26 '19 at 16:12
  • The second way with the tags not nested is the preferred way for web accessibility – Tristan Forward Nov 14 '20 at 22:29
  • @TristanForward but with modern reusable components, wouldn't we have duplicate `id` tags on the dom? Isn't that "bad"? – adamdport May 23 '22 at 21:08
  • 1
    @adamdport You can generate unique IDs for the inputs. – Barmar May 23 '22 at 21:12
  • @Andy Your edit describes the purpose of the ` – Barmar Jul 13 '22 at 15:21
  • Not really. Without the for, the input itself does not have an accessible name – Andy Jul 13 '22 at 18:03
  • @Andy As I say in the answer, you can wrap the label around the input. `for` is only needed when you don't use the wrapping form – Barmar Jul 13 '22 at 18:57
  • I’m not really sure whether I get your point, but I tried to rephrase the a11y notice to apply fit better with the preceding text. – Andy Jul 14 '22 at 13:04
64

The for attribute associates the label with a control element, as defined in the description of label in the HTML 4.01 spec. This implies, among other things, that when the label element receives focus (e.g. by being clicked on), it passes the focus on to its associated control. The association between a label and a control may also be used by speech-based user agents, which may give the user a way to ask what the associated label is, when dealing with a control. (The association may not be as obvious as in visual rendering.)

In the first example in the question (without the for), the use of label markup has no logical or functional implication – it’s useless, unless you do something with it in CSS or JavaScript.

HTML specifications do not make it mandatory to associate labels with controls, but Web Content Accessibility Guidelines (WCAG) 2.0 do. This is described in the technical document H44: Using label elements to associate text labels with form controls, which also explains that the implicit association (by nesting e.g. input inside label) is not as widely supported as the explicit association via for and id attributes,

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
  • 11
    +1 for talking about the semantic relationship and what it means beyond the functional clicking relationship. – ulty4life Aug 13 '15 at 19:00
  • 1
    Hi, I have two elements with the same id but in different div, I added focus event using label for but in second element it is focusing on first element.
    – LoveToCode Aug 01 '19 at 06:19
  • The HTML specification dictates that ids need to be unique. Having duplicate ids is not supported and will have unintended consequences like what you're experiencing. – cyberconte Apr 16 '21 at 05:46
16

In a nutshell what it does is refer to the id of the input, that's all:

<label for="the-id-of-the-input">Input here:</label>
<input type="text" name="the-name-of-input" id="the-id-of-the-input">
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 7
    Adding a for is important, even if they are adjacent. I seem to recall hearing that some screen readers for the visually impaired have problems otherwise. So if you want to be friendly to those who are perhaps using alternate browsers/screen readers, use this method. – bean5 Apr 14 '15 at 21:22
4

Using label for= in html form

This could permit to visualy dissociate label(s) and object while keeping them linked.

Sample: there is a checkbox and two labels.

  • You could check/uncheck the box by clicking indifferently on

    • any label or
    • on checkboxes,

    but not on text nor on input content...

<label for="demo1"> There is a label </label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1"> There is a 2nd label </label>
<input id="demo1" type="checkbox">Demo 1</input>

Some useful tricks

Same sample, but with two checkboxes and some different CSS effects (like writting in text: Select this or Deselect this reflecting checkbox state.).

By using stylesheet CSS power you can do a lot of interesting things...

body { background: #DDD; } 
.button:before { content: 'S'; }
.box:before { content: '☐'; }
label.button   { background: #BBB;
    border-top: solid 2px white;border-left: solid 2px white;
    border-right: solid 2px black;border-bottom: solid black 2px; }

#demo2:checked ~ .but2:before { content: 'Des'; }
#demo2:checked ~ .but2  { background: #CCC;
    border-top: solid 2px black;border-left: solid 2px black;
    border-right: solid 2px white;border-bottom: solid white 2px; }
#demo2:checked ~ .box2:before { content: '☒'; }

#demo1:checked ~ .but1  { background: #CCC;
    border-top: solid 2px black;border-left: solid 2px black;
    border-right: solid 2px white;border-bottom: solid white 2px; }

#demo1:checked ~ .but1:before { content: 'Des'; }
#demo1:checked ~ .box1:before { content: '☒'; }
<input id="demo1" type="checkbox">Demo 1</input>
<input id="demo2" type="checkbox">Demo 2</input>
<br />
<label for="demo1" class="button but1">elect 1</label> - 
<label for="demo2" class="button but2">elect 2</label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis ...
<br />
<label for="demo1" class="but1 button">elect this 2nd label for box 1</label> - 
<label class="but2 button" for="demo2">elect this other 2nd label for box 2</label>
<br /><br />
<label for="demo1" class="box box1"> check 1</label>
<label for="demo2" class="box2 box"> check 2</label>

Usage sample: Toggle sidebar using CSS only (2nd snippet).

In this answer, I use only CSS and label for to add a sidebar which could be toggled without the use of any javascript code.

F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
  • This answer was posted 7 years, 4 months, 4 weeks, 2 days, 11 am, 26 minutes and 29 seconds after the question. His first *upvote* has been granted 1 year, 3 weeks, 4 days, 13 hours, 35 minutes and 42 seconds later ... – F. Hauri - Give Up GitHub Feb 03 '22 at 07:14
  • I never thought of it as providing multiple things you can click on to set the one and only checkbox. I like it – J_McCaffrey Feb 10 '22 at 01:05
  • @J_McCaffrey If you liked this, maybe would you like the usage sample: [Toggle sidebar using CSS only](https://stackoverflow.com/a/30311244/1765658) look at 2nd snippet: *toggle:checked*. – F. Hauri - Give Up GitHub Feb 10 '22 at 06:57
2

The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 10
    Yes, but what do you mean by "bind them together" ? They are already neighbors in HTML structure. This is what I don't understand. – jeff Aug 25 '13 at 18:43
  • 2
    FOR Specifies which form element a label is bound to – Rahul Tripathi Aug 25 '13 at 18:44
  • 2
    @CengizFrostclaw http://jsfiddle.net/DmSGh/ --- try clicking on both of the "Input here" texts and see what happens. – JJJ Aug 25 '13 at 18:45
  • 1
    @CengizFrostclaw:- A label can be bound to an element either by using the "for" attribute – Rahul Tripathi Aug 25 '13 at 18:46
  • 1
    There are some nice features for example when you are using radio buttons. Clicking on the label will actually toggle the radio button. This is a nice feature when you try to use radio buttons with a custom ui. – Alex Aug 25 '13 at 18:46
  • Have a look at these features:- http://www.euclidsfifth.com/development/for-attribute-used-wit-label-tags/ and http://www.webmasterworld.com/forum21/7407.htm – Rahul Tripathi Aug 25 '13 at 18:51
0

The for attribute shows that this label stands for related input field, or check box or radio button or any other data entering field associated with it. for example

<li>
    <label>{translate:blindcopy}</label>
    <a class="" href="#" title="{translate:savetemplate}" onclick="" ><i class="fa fa-list" class="button" ></i></a> &nbsp 
            <input type="text" id="BlindCopy" name="BlindCopy" class="splitblindcopy" />

</li>
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Pax
  • 65
  • 1
  • 4
  • 19
-1

It labels whatever input is the parameter for the for attribute.

<input id='myInput' type='radio'>
<label for='myInput'>My 1st Radio Label</label>
<br>
<input id='input2' type='radio'>
<label for='input2'>My 2nd Radio Label</label>
<br>
<input id='input3' type='radio'>
<label for='input3'>My 3rd Radio Label</label>
pythag0ras_
  • 122
  • 11