Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If the w3.org HTML5 form spec nests an <input> inside a parent <label>, why do most pages implement them as siblings?

Tags:

html

w3c

I've been reading the w3.org HTML5 form spec, and was surprised to see the following HTML:

<p><label>Customer name: <input name="custname"></label></p>
<p><label>Telephone: <input type=tel name="custtel"></label></p>
<p><label>E-mail address: <input type=email name="custemail"></label></p>

Semantically, this confuses me. Wouldn't a <label> make more sense as a sibling to an <input>, rather than as its parent?

In the wild, I'm more used to seeing the following configuration:

<p>
  <label for="customer_name">Customer name:</label>
  <input id="customer_name" name="customer[name]">
</p>

I know that a large majority of markup out there is malformed, but I'm interested to hear others' thoughts on what the proper convention should be.

I stand corrected, but it seems every markup generator and form helper I've used essentially violates the W3's suggestions - even those that claim HTML5 support, making use of client-side validations and the like.

Thoughts?

like image 605
Jeriko Avatar asked Oct 30 '11 12:10

Jeriko


1 Answers

Both forms are valid, per the spec:

The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable form-associated element in the same Document as the label element. If the attribute is specified and there is an element in the Document whose ID is equal to the value of the for attribute, and the first such element is a labelable form-associated element, then that element is the label element's labeled control.

If the for attribute is not specified, but the label element has a labelable form-associated element descendant, then the first such descendant in tree order is the label element's labeled control.

You can either use nesting, if that makes sense for your markup, or use the for attribute if you're unable to use implicit nesting. Neither is more or less correct than the other. I presume most people favor using the for attribute since that gives the author the most flexibility by allowing the two elements to be decoupled from each other.

like image 193
pbyrne Avatar answered Oct 31 '22 00:10

pbyrne