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

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.

Related

Can I put checkbox and hidden input inside a label?

I have a list of possible products a user can buy. For doing it, I use ul tag combined with li.
Every element has a checkbox that allows the user to choose if select the product or not.
Some products have related information. In order to describe this, I would like to store the data inside an hidden input. But because the selection and the information are related to a product I thought to use a label that contains the checkbox and the hidden input.
Something like
<label class="product">
<input class="product-checkbox" name="product1" type="checkbox">
<input type="hidden" name="product1-information" value="{...}" />
<span class="product-name">Product1</span>
</label>
If I understood correctly, a label cannot refer to an hidden input but in the above example, accordingly to the w3c, the labeled control is the checkbox.
Anyway I'm wandering if a label can contains checkbox and an hidden input.
So, is the above snipper correct?
You're right on both counts. From MDN
The form control that a label is labeling is called the labeled control of the label element. Multiple labels can be associated with the same form control:
<label for="username">Enter your username:</label>
<input id="username">
<label for="username">Forgot your username?</label>
Elements that can be associated with a <label> element include <button>, <input> (except for type="hidden"), <meter>, <output>, <progress>, <select> and <textarea>.
(emphasis mine)
That makes it pretty clear to me that (a) multiple things inside a <label> block is entirely acceptable, and (b) hidden inputs will not be considered targets of the label.

Difference between for and aria-labeled-by

Can sommeone explain me the difference between using the for-attribute on a label and using the aria-labelled-by-attribute on the input.
As far as I know aria-labelled-by allows multiple elements (e.g.radio buttons) to be labelled by the same label whether for relies on the id of the elements which should be unique and can therefore only assigned to one element.
So in which case should I use for and in which case aria-labelled-by?
The main difference is that for attribute has the functional purpose. for attribute is used to chain the label with specified form field of some id. For example:
<div>
<input type="checkbox" id="checkboxId" />
<label for="checkboxId">My cool checkbox with clickable label</label>
</div>
<div>
<input type="checkbox" id="checkboxId2" />
<label>My cool checkbox without clickable label</label>
</div>
As you can see, the label with specified for attrubute has ability to toggle checkbox of id that is specified in this for attribute.
The ARIA attributes are mainly used to make you application accessible for people with some kind of disabilities (e. g. to make you application suitable with screen-readers, etc.). The ARIA attributes have no direct functional purposes, they are only about accessibility
<input aria-labeledby="myLabel" type="checkbox" id="checkboxId" />
<label id="myLabel">My cool label</label>

Does <label> for attribute has to be unique?

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.

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

Should I put input elements inside a label element?

Is there a best practice concerning the nesting of label and input HTML elements?
classic way:
<label for="myinput">My Text</label>
<input type="text" id="myinput" />
or
<label for="myinput">My Text
<input type="text" id="myinput" />
</label>
From the W3's HTML4 specification:
The label itself may be positioned before, after or around the
associated control.
<label for="lastname">Last Name</label>
<input type="text" id="lastname" />
or
<input type="text" id="lastname" />
<label for="lastname">Last Name</label>
or
<label>
<input type="text" name="lastname" />
Last Name
</label>
Note that the third technique cannot be used when a table is being used for layout, with the label in one cell and its associated form field in another cell.
Either one is valid. I like to use either the first or second example, as it gives you more style control.
I prefer
<label>
Firstname
<input name="firstname" />
</label>
<label>
Lastname
<input name="lastname" />
</label>
over
<label for="firstname">Firstname</label>
<input name="firstname" id="firstname" />
<label for="lastname">Lastname</label>
<input name="lastname" id="lastname" />
Mainly because it makes the HTML more readable. And I actually think my first example is easier to style with CSS, as CSS works very well with nested elements.
But it's a matter of taste I suppose.
If you need more styling options, add a span tag.
<label>
<span>Firstname</span>
<input name="firstname" />
</label>
<label>
<span>Lastname</span>
<input name="lastname" />
</label>
Code still looks better in my opinion.
Behavior difference: clicking in the space between label and input
If you click on the space between the label and the input it activates the input only if the label contains the input.
This makes sense since in this case the space is just another character of the label.
div {
border: 1px solid black;
}
label {
border: 1px solid black;
padding: 5px;
}
input {
margin-right: 30px;
}
<p>Inside:</p>
<label>
<input type="checkbox" />
Label. Click between me and the checkbox.
</label>
<p>Outside:</p>
<input type="checkbox" id="check" />
<label for="check">Label. Click between me and the checkbox.</label>
Being able to click between label and box means that it is:
easier to click
less clear where things start and end
Bootstrap checkbox v3.3 examples use the input inside: http://getbootstrap.com/css/#forms Might be wise to follow them. But they changed their minds in v4.0 https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios so I don't know what is wise anymore:
Checkboxes and radios use are built to support HTML-based form validation and provide concise, accessible labels. As such, our <input>s and <label>s are sibling elements as opposed to an <input> within a <label>. This is slightly more verbose as you must specify id and for attributes to relate the <input> and <label>.
UX question that discusses this point in detail: https://ux.stackexchange.com/questions/23552/should-the-space-between-the-checkbox-and-label-be-clickable
If you include the input tag in the label tag, you don't need to use the 'for' attribute.
That said, I don't like to include the input tag in my labels because I think they're separate, not containing, entities.
Personally I like to keep the label outside, like in your second example. That's why the FOR attribute is there. The reason being I'll often apply styles to the label, like a width, to get the form to look nice (shorthand below):
<style>
label {
width: 120px;
margin-right: 10px;
}
</style>
<label for="myinput">My Text</label>
<input type="text" id="myinput" /><br />
<label for="myinput2">My Text2</label>
<input type="text" id="myinput2" />
Makes it so I can avoid tables and all that junk in my forms.
See http://www.w3.org/TR/html401/interact/forms.html#h-17.9 for the W3 recommendations.
They say it can be done either way. They describe the two methods as explicit (using "for" with the element's id) and implicit (embedding the element in the label):
Explicit:
The for attribute associates a label with another control explicitly: the value of the for attribute must be the same as the value of the id attribute of the associated control element.
Implicit:
To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element.
Both are correct, but putting the input inside the label makes it much less flexible when styling with CSS.
First, a <label> is restricted in which elements it can contain. For example, you can only put a <div> between the <input> and the label text, if the <input> is not inside the <label>.
Second, while there are workarounds to make styling easier like wrapping the inner label text with a span, some styles will be in inherited from parent elements, which can make styling more complicated.
3rd party edit
According to my understanding html 5.2 spec for label states that the labels Content model is Phrasing content. This means only tags whose content model is phrasing content <label> are allowed inside </label>.
Content model A normative description of what content must be included
as children and descendants of the element.
Most elements that are categorized as phrasing content can only
contain elements that are themselves categorized as phrasing content,
not any flow content.
A notable 'gotcha' dictates that you should never include more than one input element inside of a <label> element with an explicit "for" attribute, e.g:
<label for="child-input-1">
<input type="radio" id="child-input-1"/>
<span> Associate the following text with the selected radio button: </span>
<input type="text" id="child-input-2"/>
</label>
While this may be tempting for form features in which a custom text value is secondary to a radio button or checkbox, the click-focus functionality of the label element will immediately throw focus to the element whose id is explicitly defined in its 'for' attribute, making it nearly impossible for the user to click into the contained text field to enter a value.
Personally, I try to avoid label elements with input children. It seems semantically improper for a label element to encompass more than the label itself. If you're nesting inputs in labels in order to achieve a certain aesthetic, you should be using CSS instead.
As most people have said, both ways work indeed, but I think only the first one should. Being semantically strict, the label does not "contain" the input. In my opinion, containment (parent/child) relationship in the markup structure should reflect containment in the visual output. i.e., an element surrounding another one in the markup should be drawn around that one in the browser. According to this, the label should be the input's sibling, not it's parent. So option number two is arbitrary and confusing. Everyone that has read the Zen of Python will probably agree (Flat is better than nested, Sparse is better than dense, There should be one-- and preferably only one --obvious way to do it...).
Because of decisions like that from W3C and major browser vendors (allowing "whichever way you prefer to do it", instead of "do it the right way") is that the web is so messed up today and we developers have to deal with tangled and so diverse legacy code.
I usually go with the first two options. I've seen a scenario when the third option was used, when radio choices where embedded in labels and the css contained something like
label input {
vertical-align: bottom;
}
in order to ensure proper vertical alignment for the radios.
I greatly prefer to wrap elements inside my <label> because I don't have to generate the ids.
I am a Javascript developer, and React or Angular are used to generate components that can be reused by me or others. It would be then easy to duplicate an id in the page, leading there to strange behaviours.
Referring to the WHATWG (Writing a form's user interface) it is not wrong to put the input field inside the label. This saves you code because the for attribute from the label is no longer needed.
One thing you need to consider is the interaction of checkbox and radio inputs with javascript.
Using below structure:
<label>
<input onclick="controlCheckbox()" type="checkbox" checked="checkboxState" />
<span>Label text</span>
</label>
When user clicks on "Label text" controlCheckbox() function will be fired once.
But when input tag is clicked the controlCheckbox() function may be fired twice in some older browsers. That's because both input and label tags trigger onclick event attached to checkbox.
Then you may have some bugs in your checkboxState.
I've run into this issue lately on IE11. I'm not sure if modern browsers have troubles with this structure.
There are several advantages of nesting the inputs into a label, especially with radio/checkbox fields,
.unchecked, .checked{display:none;}
label input:not(:checked) ~ .unchecked{display:inline;}
label input:checked ~ .checked{display:inline;}
<label>
<input type="checkbox" value="something" name="my_checkbox"/>
<span class="unchecked">Not Checked</span>
<span class="checked">Is Checked</span>
</label>
As you can see from the demo, nesting the input field first followed by other elements allows,
The text to be clicked to activate the field
The elements following the input field to be dynamically styled according to the status of the field.
In addition, HTML std allows multiple labels to be associated with an input field, however this will confuse screen readers and one way to get round this is to nest the input field and other elements within a single label element.