Does <label> for attribute has to be unique? - html

Can I have two labels with the same for value? Example:
<label for="foo">Outer label</label>
<div class="foo-bar">
<input type="checkbox" id="foo" />
<label for="foo">Inner label</label>
</div>

The for attribute links a control to an input, there is, so far as I know, no limit to the number of elements that can link to one input, so long as the id of that input (or textarea, select, etc) is unique.
For example, in the following demo both label elements will trigger the change (check/uncheck) of the checkbox input element:
<label for="foo">Outer label</label>
<div class="foo-bar">
<input type="checkbox" type="checkbox" name="test" id="foo" />
<label for="foo">Inner label</label>
</div>
JS Fiddle demo.
This can be useful for adding error messages (post-validation, for example) that explicitly link to, or otherwise identify, the element in which there's an error, without overriding/replacing the pre-existing label for that element.
Unfortunately there is, so far as I've yet found, no reference or documentation that explicitly allows an input (or similar element) to linked to only one control; however MDN's entry for <label> does state that:
The ID of a labelable form-related element in the same document as the label element. The first such element in the document with an ID matching the value of the for attribute is the labeled control for this label element.

Related

Why do we use "for" attribute inside label tag?

I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand
Code1
<input id="indoor" type="radio" name="indoor-outdoor">
<label for="indoor">Indoor</label>
Code2
<label for="loving"><input id="loving" type="checkbox" name="personality"> Loving</label>
<br>
<label><input type="checkbox" name="personality"> Loving</label>
I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them.
Any help?
It is correct, that it works without it. But it is useful to connect the label with the input field. That is also important for the accessibility (e.g. for blind people, the text is read).
The browsers also allow you to click the labels and automatically focus the input fields.
For checkboxes this can be useful as well. But for these, you could also surround the checkbox-input like this:
<label>
<input type="checkbox"> I agree with the answer above.
</label>
In this case, the checkbox is automatically checked when you click on the text.
The surrounding of the inputs with a label works with every input field. But the text, that describes the input field, should always be inside it. That what for is for: When your HTML disallows the label-surrounding, you can use the for-attribute.
The the both following examples:
Simple stuctured:
<label>
Your Name:<br>
<input type="text"/>
</label>
Complex structure around input fields:
<div class="row">
<div class="col">
<label for="name">Your Name:</label>
</div>
<div class="col">
<input type="text" id="name" />
</div>
</div>
It could be used without "for" attribute, and it will be fine, according to docs.
This is just one option how to use "for" to omit confusing developers.
Anyway, in case of placing checkbox inside label, you can skip "for" and it will be fine.
<!-- labelable form-relation still works -->
<label><input type="checkbox" name="personality"> Loving</label>
"for" approach much preferable if you want to style it, f.e. using Bootstrap
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">
Default checkbox
</label>
</div>
To be able to use the label with the check box.
E.g., when rendered, click the label and it will toggle the check box ticked state.
Edit: Further to this, it allows putting the label anywhere on the page.

Using <label for=""> with a HtmlHelper rendered element with an id that contains a space

If I have a plain checkbox <input> element with an id attribute that contains a space, I can still use <label for=""> to bind a label to the element, and then click on the label text to toggle the checkbox value:
<input type="checkbox" id="remember me" />
<label for="remember me">Remember me</label>
However, if I create the same <input> element using the HtmlHelper class, <label for=""> does not seem to bind the label to the label text. When I click on the label text, the checkbox does not toggle:
#Html.CheckBox("remember me")
<label for="remember me">Remember me</label>
Why is the behavior differing when I use HtmlHelper? Is it possible to use <label for=""> with a HtmlHelper rendered element that has an id that contains a space?
Please note, the main purpose of this question is to document something interesting that I discovered. According to HTML 5 standards, the id attribute should be at least one character, and should not contain any space characters. I came across some code that obviously didn't follow the W3C recommendations, and while cleaning it up, found a solution for the above problem, so I figured I may as well share what I found in case this can help someone in the future.
When the HtmlHelper creates the <input> element, it replaces all spaces in the id attribute with underscores.
If you inspect the rendered HTML code, you will see the the input element renders as follows:
<input id="remember_me" name="remember me" value="true" type="checkbox">
If you want to associate a label with the above element, therefore, you need to replace all spaces with underscores in the forstring:
#Html.CheckBox("remember me")
<label for="remember_me">Remember me</label>
Another way you can possibly avoid the above problem is by skipping the for="" attribute all together, and just wrapping the <label> tag around the entire input element:
<label>
#Html.CheckBox("remember me")
Remember me
</label>
I've found this solution to sometimes causes issues, however, if I had some CSS styles set for all label elements, and didn't want the styles applied to all the elements that the label surrounded.

Can an html label tag have more than one "for" attribute? [duplicate]

Consider the following:
<label>Range from
<input name='min_value'/> to
<input name='max_value' />
</label>
Is this semantically correct since the W3C recommendations state that a label is associated with exactly one form control?
Clicking into the second input shifts focus immediately to the first input? Can this be prevented?
How would one markup a min/max input combination to show that two inputs belong together?
No, it's not correct (since, as you note, a label is associated with exactly one form input).
To label a group of inputs that belong together, use a <fieldset> and a <legend>:
<fieldset>
<legend>Range</legend>
<label for="min">Min</label>
<input id="min" name="min" />
<label for="max">Max</label>
<input id="max" name="max" />
</fieldset>
References:
<input />HTML 5 spec.
<fieldset>HTML 5 spec.
<label>HTML 5 spec.
<legend>HTML 5 spec.
As the accepted answer states, that's not correct, however I think there are better ways to do it.
Accessible alternatives:
Option 1 (using the aria-label attribute):
Range:
<input ... aria-label='Range start' />
<input ... aria-label='Range end' />
Option 2 (using hidden label tags):
<label for='start'>Range start</label>
<input type='text' id='start' />
<label for='end' class='hidden'>Range end</label>
<input type='text' id='end' />
Where the .hidden class is only readable by screen readers.
Option 3 (using aria-labelledby attributes):
<label id='lblRange'>Range</label>
<input type='text' id='start' aria-labelledby='lblRange' />
<input type='text' id='end' aria-labelledby='lblRange' />
Advantages of option #1: Each input has a good description that other suggestions (such adding a "to" label) do not. Options #2 and #3 might not be the best for this specific case, but worth mentioning for similar cases.
Source: http://webaim.org/techniques/forms/advanced
I see many answers saying it is wrong to put 2 inputs inside a label.
This is actually a wrong statement in html5. The standard explicitly allow it:
http://www.w3.org/TR/html5/forms.html#the-label-element
If the for attribute is not specified, but the label element has a labelable element descendant, then the first such descendant in tree order is the label element’s labeled control.
If a label element has interactive content other than its labeled control, the activation behavior of the label element for events targeted at those interactive content descendants and any descendants of those must be to do nothing.
However, Safari does not respect the html5 standard here (tested on iOS 11.3). So, someone that wants to be compatible with Safari must use workarounds here or wait until Apple fixes its browser.
According to this - label can contain only one input as it should be associated with only one control. Putting input inside the label means elimination of for attribute (automatic linking).
So you should either put single input into label or specify for attribute which points to input id and don't put input into label.
How about this:
<label> Range from <input name='min_value'> </label>
<label> to <input name='max_value'> </label>
1 LABEL = 1 INPUT !!!
If you put 2 INPUTS inside a LABEL, it will NOT work in Safari (and iPad and iPhone)... because when you click inside LABEL it automatically focuses the first INPUT... so the second input is impossible to type to.
I see many answers saying it is wrong to put 2 inputs inside a label. This is actually a wrong statement in html5. The standard explicitly allow it: http://www.w3.org/TR/html5/forms.html#the-label-element
<label id='dobRange'>DOB between</label>
<input type='text' id='start' aria-labelledby='dobRange' />
<input type='text' id='end' aria-labelledby='dobRange' />
in haml:
= f.label :dob_range
= f.search_field :dob_gteq, 'aria-label': 'dob_range'
= f.search_field :dob_lteq, 'aria-label': 'dob_range'
i don't think you should be putting the input field inside the label control.
<label for="myfield">test</label><input type="text" id="myfield" name="myfield />
the label is just that, a label for something.

What is the HTML for="" attribute in <label>?

I have seen this in jQuery - what does it do?
<label for="name"> text </label>
<input type="text" name="name" value=""/>
The for attribute is used in labels. It refers to the id of the element this label is associated with.
For example:
<label for="username">Username</label>
<input type="text" id="username" name="username" />
Now when the user clicks with the mouse on the username text the browser will automatically put the focus in the corresponding input field. This also works with other input elements such as <textbox> and <select>.
Quote from the specification:
This attribute explicitly associates the label being defined with
another control. When present, the value of this attribute must be the
same as the value of the id attribute of some other control in the
same document. When absent, the label being defined is associated with
the element's contents.
As far as why your question is tagged with jQuery and where did you see it being used in jQuery I cannot answer because you didn't provide much information.
Maybe it was used in a jQuery selector to find the corresponding input element given a label instance:
var label = $('label');
label.each(function() {
// get the corresponding input element of the label:
var input = $('#' + $(this).attr('for'));
});
To associate the <label> with an <input> element, you need to give the <input> an id attribute. The <label> then needs a for attribute whose value is the same as the input's id:
<label for="username">Click me</label>
<input type="text" id="username">
The for attribute associates a <label> with an <input> element; which offers some major advantages:
1. The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screen reader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
2. You can click the associated label to focus/activate the input, as well as the input itself. This increased hit area provides an advantage to anyone trying to activate the input, including those using a touch-screen device.
Alternatively, you can nest the <input> directly inside the <label>, in which case the for and id attributes are not needed because the association is implicit:
<label>Click me <input type="text"></label>
Notes:
One input can be associated with multiple labels.
When a <label> is clicked or tapped and it is associated with a form control, the resulting click event is also raised for the associated control.
Accessibility concerns
Don't place interactive elements such as anchors or buttons inside a label. Doing so, makes it difficult for people to activate the form input associated with the label.
Headings
Placing heading elements within a <label> interferes with many kinds of assistive technology, because headings are commonly used as a navigation aid. If the label's text needs to be adjusted visually, use CSS classes applied to the <label> element instead.
If a form, or a section of a form needs a title, use the <legend> element placed within a <fieldset>.
Buttons
An <input> element with a type="button" declaration and a valid value attribute does not need a label associated with it. Doing so may actually interfere with how assistive technology parses the button input. The same applies for the <button> element.
Ref:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
I feel the need to answer this. I had the same confusion.
<p>Click on one of the text labels to toggle the related control:</p>
<form action="/action_page.php">
<label for="female">Male</label>
<input type="radio" name="gender" id="male" value="male"><br>
<label for="female">Female</label>
<input type="radio" name="gender" id="female" value="female"><br>
<label for="other">Other</label>
<input type="radio" name="gender" id="other" value="other"><br><br>
<input type="submit" value="Submit">
</form>
I changed the for attribute on the 'male' label to female. Now, if you click 'male' the 'female' radio will get checked.
Simple as that.
a fast example:
<label for="name">Name:</label>
<input id="name" type="text" />
the for="" tag let focus the input when you click the label as well.
You use it with labels to say that two objects belong together.
<input type="checkbox" name="remember" id="rememberbox"/>
<label for="rememberbox">Remember your details?</label>
This also means that clicking on that label will change the value of the checkbox.
FYI - if you are in an typescript environment with e.g.
<label for={this.props.inputId}>{this.props.label}</label>
you need to use htmlFor
<label htmlFor={this.props.inputId}>{this.props.label}</label>
it is used for <label> element
it is used with input type checkbox or redio to select on label click
working demo
The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together.
It associates the label with an input element. HTML tags are meant to convey special meaning to users of various categories. Here is what label is meant for:
For people with motor disabilities (also for general mouse users): Correctly used label tags can be clicked to access the associated form control. Eg. Instead of particularly clicking the checkbox, user can click on more easily clickable label and toggle the checkbox.
For visually-challenged users: Visually challenged users use screen-readers that reads the associated label tag whenever a form control is focused. It helps users to know the label which was otherwise invisible to them.
More about labelling -> https://www.w3.org/TR/WCAG20-TECHS/H44.html
it is used in <label> text for html
eg.
<label for="male">Male</label>
<input type="radio" name="sex" id="male" value="male"><br>
It's the attribute for <label> tag : http://www.w3schools.com/tags/tag_label.asp

Two input fields inside one label

Consider the following:
<label>Range from
<input name='min_value'/> to
<input name='max_value' />
</label>
Is this semantically correct since the W3C recommendations state that a label is associated with exactly one form control?
Clicking into the second input shifts focus immediately to the first input? Can this be prevented?
How would one markup a min/max input combination to show that two inputs belong together?
No, it's not correct (since, as you note, a label is associated with exactly one form input).
To label a group of inputs that belong together, use a <fieldset> and a <legend>:
<fieldset>
<legend>Range</legend>
<label for="min">Min</label>
<input id="min" name="min" />
<label for="max">Max</label>
<input id="max" name="max" />
</fieldset>
References:
<input />HTML 5 spec.
<fieldset>HTML 5 spec.
<label>HTML 5 spec.
<legend>HTML 5 spec.
As the accepted answer states, that's not correct, however I think there are better ways to do it.
Accessible alternatives:
Option 1 (using the aria-label attribute):
Range:
<input ... aria-label='Range start' />
<input ... aria-label='Range end' />
Option 2 (using hidden label tags):
<label for='start'>Range start</label>
<input type='text' id='start' />
<label for='end' class='hidden'>Range end</label>
<input type='text' id='end' />
Where the .hidden class is only readable by screen readers.
Option 3 (using aria-labelledby attributes):
<label id='lblRange'>Range</label>
<input type='text' id='start' aria-labelledby='lblRange' />
<input type='text' id='end' aria-labelledby='lblRange' />
Advantages of option #1: Each input has a good description that other suggestions (such adding a "to" label) do not. Options #2 and #3 might not be the best for this specific case, but worth mentioning for similar cases.
Source: http://webaim.org/techniques/forms/advanced
I see many answers saying it is wrong to put 2 inputs inside a label.
This is actually a wrong statement in html5. The standard explicitly allow it:
http://www.w3.org/TR/html5/forms.html#the-label-element
If the for attribute is not specified, but the label element has a labelable element descendant, then the first such descendant in tree order is the label element’s labeled control.
If a label element has interactive content other than its labeled control, the activation behavior of the label element for events targeted at those interactive content descendants and any descendants of those must be to do nothing.
However, Safari does not respect the html5 standard here (tested on iOS 11.3). So, someone that wants to be compatible with Safari must use workarounds here or wait until Apple fixes its browser.
According to this - label can contain only one input as it should be associated with only one control. Putting input inside the label means elimination of for attribute (automatic linking).
So you should either put single input into label or specify for attribute which points to input id and don't put input into label.
How about this:
<label> Range from <input name='min_value'> </label>
<label> to <input name='max_value'> </label>
1 LABEL = 1 INPUT !!!
If you put 2 INPUTS inside a LABEL, it will NOT work in Safari (and iPad and iPhone)... because when you click inside LABEL it automatically focuses the first INPUT... so the second input is impossible to type to.
I see many answers saying it is wrong to put 2 inputs inside a label. This is actually a wrong statement in html5. The standard explicitly allow it: http://www.w3.org/TR/html5/forms.html#the-label-element
<label id='dobRange'>DOB between</label>
<input type='text' id='start' aria-labelledby='dobRange' />
<input type='text' id='end' aria-labelledby='dobRange' />
in haml:
= f.label :dob_range
= f.search_field :dob_gteq, 'aria-label': 'dob_range'
= f.search_field :dob_lteq, 'aria-label': 'dob_range'
i don't think you should be putting the input field inside the label control.
<label for="myfield">test</label><input type="text" id="myfield" name="myfield />
the label is just that, a label for something.