What's the best way to wrap Label and Input elements - html

I'm working on a HTML5 form and I want to float some input elements and their labels. Its this the best way to do it?
<form>
<fieldset class="float_left">
<label for="login">Login ID #</label>
<input type="text" name="login" id="login">
</fieldset>
<fieldset class="float_right">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</fieldset>
<span class="forgot_login float_left">Forgot your login information?</span>
<input type="submit" value="LOG IN" class="form_button float_right">
</form>
I seen people wrap them in divs, lists, etc. I want to follow the best practice. Should I also wrap every label and input elements with a fieldset even if I don't plan on styling it? Ex:
<form>
<fieldset>
<label for="name">Full Name:</label>
<input type="text" name="name" id="name" placeholder="First Name" class="float_left">
</fieldset>
<fieldset>
<label for="email">Email:</label>
<input type="email" name="email" id="email" placeholder="Ex: johndoe#gmail.com" class="full_input">
</fieldset>
<fieldset>
<textarea rows="3" name="message" id="message" placeholder="1000 Character or less" class="full_input"></textarea>
</fieldset>
<input type="submit" value="SEND" class="form_button float_right">
</form>
Thanks.

The primary, original purpose of a fieldset is to convey a contextual association between multiple input fields to non-visual agents. It is expected that a screen reader is going to read the legend text, then the first field, then the legend, then the next field... As in: "Address: Street 1... Address: Street 2... Address: City..."
For sighted people, a fieldset does visually imply a container-type relationship of the same kind: those fields are related by context, but only when there are multiple fields.
So it never makes semantic sense to have a single label/field (a label is not a field, in that it does not accept input) in a fieldset. It's just annoying to people using screen readers (because it behaves like a redundant label). To sighted people it destroys the implication of relationship if you use it for single fields and also multiple fields, and takes up a lot more space.
In short, use it sparingly, semantically, and correctly - not as a styling device.
For a 'neutral' container, use a div or a span, because they carry no semantic information. List structures, paragraphs, all other elements have semantics and you need to be careful about how you use them.
People will tell you crazy things about the semantics of HTML elements. Don't take anyone at their word, including me. Go read the spec and know it for yourself.

Using fieldset for a combination of a label and a control is illogical, though formally valid: a fieldset is supposed to be a set of fields.
Other than that, the question is largely a matter of opinion and debate. HTML5 more or less favors p for such a pair, but that causes an empty line by default, so div is a more reasonable choice. There are also good reasons to use a table element, with one row for each label/control pair.

Unless you plan to use a fieldset legend then I wouldn't bother using fieldsets. Bootstrap forms is a nice way to get started too http://getbootstrap.com/css/#forms there is no best way though.
You often see people using a wrapper div because it helps with creating a neater row i.e. apply padding to a wrapper instead of to all elements within it or floating all elements within a parent and applying a clear-fix element at the bottom to wrap correctly.. or just float the parent as well.

Related

Accessibility and complex HTML forms: How to use headings between form controls?

A client needs to create quite a complex form. We use <fieldset>/<legend> to group certain elements together. But it's not enough - even if we nest them.
Think about the following:
<form>
<fieldset>
<legend>Your personal details</legend>
<label>First name: <input name="first_name"></label>
<label>Last name: <input name="last_name"></label>
<fieldset>
<legend>Gender</legend>
<label>Male: <input type="radio" name="gender" value="male"></label>
<label>Female: <input type="radio" name="gender" value="female"></label>
<label>Other: <input type="radio" name="gender" value="other"></label>
</fieldset>
</fieldset>
</form>
Imagine this is only a small part of a bigger form. For example, we could have a "postal address" and a "billing address". Would we need to "indent" the whole thing once more using <fieldset>/<legend>s?
<form>
<fieldset>
<legend>Postal address</legend>
<fieldset>
<legend>Your personal details</legend>
...
<fieldset>
<legend>Gender</legend>
...
</fieldset>
</fieldset>
</fieldset>
<fieldset>
<legend>Billing address</legend>
...
</fieldset>
</form>
Or should we rather use headings?
<form>
<h2>Postal address</h2>
<fieldset>
<legend>Your personal details</legend>
...
<fieldset>
<legend>Gender</legend>
...
</fieldset>
</fieldset>
<h2>Billing address</h2>
...
</form>
While it's probably valid to nest <fieldset>/<legend>s, I would not over-do it. Party because JAWS will announce the <legend> for each contained input element (in contrast to NVDA that will only announce it once, when reaching the first contained input element).
On the other hand, headings will not be announced at all by desktop screen readers when jumping between form elements using Tab/Shift-Tab. So its information will easily be missed.
What do you think about that, dear screen reader experts? Should we use aria-describedby to attach the headings to the subsequent <fieldset>? What if there's more than one <fieldset> below that heading?
I feel there's no perfect solution here. Any suggestions, please?
It's perfectly valid to nest fieldset+legend, but as you ahve said, some screen readers will repeat it for each of the elements under that legend.
It makes a lot of totally useless redundency.
There is certainly no perfect solution, and no normative solution on this either, but I would go for an hybrid structure.
Use legend only for the deepest level, where elements are really close together such as male/female, yes/no, etc. (i.e. groups of radio buttons), and headings for all the rest and intermediate levels. For example:
<h2>Personal information</h2>
<fieldset>
<legend>Gender</legend>
...
</fieldset>
<fieldset>
<legend>Marital status</legend>
...
</legend>
</fieldset>
<h2>Billing address</h2>
...
<h2>Delivery address</h2>
...
Headings have a great bonus advantage, there are shortcuts keys to jump directly to them. It's especially useful when you want to modify only one or two particular fields in the whole form. You can't do this with legend.
IF you are afraid that the screen reader user miss "Personal information", "Billing address" and "Delivery address", you may use aria-labelledby refering two IDs:
<h2 id="billingAddressHeading">Billing address</h2>
<p><label id="streetLabel" for=street">Street: </label>
<input type="text" aria-labelledby="streetLabel billingAddressHeading"/>
</p>
If you use two IDs like that only on the first field of the group, you make sure that the screen reader won't uselessly read the group label for each of the fields.
Be careful to not forget to reference the label itself in aria-labelledby, because it replaces completely the <label>.
Note that, technically, you are also allowed to use fieldsets without legen.
<h2 id="billingAddressHeading">Billing address</h2>
<p><label id="streetLabel" for=street">Street: </label>
<input type="text" aria-labelledby="streetLabel billingAddressHeading"/>
</p>
As a final note, if you find the form getting too complex, it's maybe the time to think about splitting it into several smaller pages.

Title for a form

I am working on an assignment and am a little lost. The question states:
Create a label element with the text Username. Within the label element, insert
an input box for the username field. Make the field required and add the title Supply
your username
Here is what I have. I am mainly confused on the title portion. Any help is greatly appreciated, and feel free to correct me on the other parts. Thank you
<form id="survey" name="survey"
action="www.sblogger/cgi-bin/subcomments"
method="post">
<fieldset id="commentFS"
<label>
Username
<input id="username">
required="required"
</label>
</fieldset>
</form>
You just need to add a title attribute on the input field. Also the label tag can stay on it's own, which leaves to:
<form id="survey"
name="survey"
action="www.sblogger/cgi-bin/subcomments"
method="post">
<fieldset id="commentFS">
<label>Username</label>
<input id="username"
title="Supply your username"
required>
</fieldset>
</form>
The assignment is not well-defined, since it does not say what kind of a title should be included. It may refer to an advisory title that may be presented to user in some situations (e.g., on mouseover), as assumed in #Jeffrey’s answer. It may also refer to text that appears inside the input box when it is empty, in which case you would use the placeholder attribute. It can also refer to visible text before the input box; this would be the most reasonable setup. Even then, there are several alternatives. It could be just text before the label and the input box, or it could be wrapped in a heading element, or even a legend for a fieldset. The following example is based on the wild assumption that such a legend is desired (which might be a wrong guess if you have actually been told to use the fieldset element, as you are using, although there is no reason to use it in a simple case like this).
<form id="survey" name="survey"
action="http://www.example.com/cgi-bin/subcomments"
method="post">
<fieldset id="commentFS">
<legend>Supply your username</legend>
<label>
Username
<input id="username" name="username"
required="required">
</label>
</fieldset>
<input type="submit" value="Submit">
</form>
Notes: The attribute required="required" (or just required unless you have been told to use XHTML syntax) must appear inside the <input ...> element, not after it. And the input element needs a name attribute, otherwise the data in it will not be sent at all to the server.

What would be the correct way to insert a form in HTML, in such a way that it's field labels are equally distanced from the input field?

Previously i have been using <table> tag in order to structure a form in such a way that we a nice formatted form so that each label and field is on line with eachother like the following:
Email: [############]
Password: [############]
However there's a semantic problem here, a form is not exactly table data. So where a table is graphically suiting, its not on a semantic level.
What would be the proper way to structure a form so it's also graphically pleasing as well as semantically correct in terms of data type?
This A List Apart article does exactly that.
It uses semantically correct tags, and CSS styling to build a table-less form with stable margins. In a nutshell, it uses label tags to display the text, and gives them fixed widths to make the form fields start at the same horizontal position.
For a solution with flexible dimensions, see Fluid input elements.
Try using <fieldset> then customizing your CSS for a better look.
<fieldset>
<legend>Login</legend>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
<br />
<label for="password">Password:</label>
<input type="password" name="password" id="password" />
<br />
</fieldset>

HTML Forms - In your opinion, how should they be done and why? (<div> vs. <p>)

I've been a developer for a long time, however forms have always been my least favourite part, more specifically designing them!
I'd really like to know how you do you forms, and why. I've had a few discussions with fellow developers over <div> vs <p> on form fields. Which one would you stick with, and why?
An example of what I am talking about:
<form action="" method="post">
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="submit"></label>
<input type="submit" name="submit" id="submit" value="Log In" />
</p>
</form>
VS
<form action="" method="post">
<div>
<label for="username">Username:</label>
<input type="text" name="username" id="username" />
</div>
<div>
<label for="submit"></label>
<input type="submit" name="submit" id="submit" value="Log In" />
</div>
</form>
When it comes to styling, it seems you can do pretty much the same with both, so is it just personal preference, or is there logic behind using one over the other?
Thanks for your time :)
UPDATE
I ended up following a nice article on HTML5 forms and have actually found it to allow MUCH better styling of forms. They are much more organised from a development perspective too. For anyone interested, it is located here: http://24ways.org/2009/have-a-field-day-with-html5-forms
HTML is all about semantics. There is no reason username or submit should be inside a paragraph (<p>) because it's not a paragraph.
So I would go using <div> instead. Ok, maybe <div> has no meaning at all. But it's better than <p>.
I prefer the <div> variant, because its semantics is closer on what you want to express and markup.
A <p> tag is for text paragraphs, whereas a <div> is a general block of any kind.
One option I'd like to suggest:
You could consider wrapping the input inside its label. That way you possibly can avoid additional elements. Also (if you don't need to support IE6) then this allows you to drop the for. And finally if the input is a check box or radio button, then it allows the user to click on the whole text instead of just the tiny control, just like in most operating systems:
<label>Username: <input type="text" name="username" /></label>
Also I'm not sure what the point of an empty label for the submit button is good for, except being lazy when writing the style sheet.
Just thought I'd throw my 2 cents in (assuming we all agree that semantic markup is the goal):
While one can argue that form elements themselves are not semantic, this doesn't mean that the context in which they appear is not as well. There is no "one true way" to markup all form controls.
If the control is actually appearing in a paragraph of text, that is fine - but that pretty much never happens.
If it is an ordered list of checkboxes for example, put them in an <ol> tag.
If order is not relevant, use a <ul> in that case.
If it is a label/text_input pair, one could argue that a <dl> element is appropriate
If it is a spreadsheet, use a <table> (Yes, tables can be appropriate! In fact, I've heard the (questionable) argument many times that form data is tabular)
By the way it is considered a description list in HTML5 to clear up confusion about meaning, and whether or not it's appropriate for things other than literal definition terms.
Almost no one will ever say a <p> is appropriate, but very few will argue that a <div> is inappropriate because there are no attached semantics.
Semantically, each label is bound to its control through the for attribute. There's no need to wrap the pair for semantic reasons, although you may wish to do so for styling reasons. So div is appropriate.
Similarly, grouping of controls has a dedicated element fieldset so there's no sense in using ul, ol or dl for that purpose, and using them is simply a form of listitis.
What about fieldsets ? - it is more logical for forms
And in fact you can style anything the way you want
Semantically I'd say divs make more sense simply because they have no semantic meaning and the only reason to use a block container like this is for layout purposes. That said, I use paragraphs, but completely out of habit. It's the only place I use paragraphs while not considering their semantic meaning.

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.