Finding a balance between label association, validation, and automatic form generation.
So we’re all aware by now that the
id attribute is supposed to occur exactly once on a page. You’re not allowed to use more than a single instance of any given
id; for that, you’d turn to a
class. Multiple classes are no problem, but multiple
Now if you’ve done you’re homework and you know how to properly apply a
label, you’ve probably run into this:
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.
This is from the spec and it basically means you should be specifying in your markup that any given
label is attached to a specific form element using the
There are a few implications from this that are just a little inconvenient. Most importantly, if you’re doing it right, this means that every single
input box on a page must have a unique
id, for the sake of its label. If you’ve ever had a page that required multiple copies of the same or similar forms, you’ll most likely have run into the validation issues this creates.
The natural tendency is simply to duplicate the forms. If you’re running script which is automating the form creation, you’ll have had to do something like
echo "<input type=\"text\" id=\"" . $formControl . $i . "\" />"; — where
$i is an incrementing value in the loop. If not, you’d have to do it by hand.
Another issue this raises is that
label elements may be associated with exactly one form control on each page. For cases where more than one element should share a common label, the only options are to over-do the labeling and selectively
display: none; the undesired labels, or you could also turn to the
legend combo… neither of which are particularly graceful in their ability to be styled, based on current browser support.
Now, both problems feel more like a design problem than a code problem — in the first case, the benefits of having duplicates of the same form on a page are questionable from a user interaction perspective, and in the second case the desire to not explicitly label a form control seems somewhat user-unfriendly. But let’s recognize that in certain cases, the best choice is an atypical operation. So what then? Extra work for you, that’s what.
Luckily though, the first problem has a fix which is old news, but I’ve only recently discovered simply by reading the spec a little more thoroughly. Implicit association means that instead of this:
<label for="myName">Your Name:</label> <input type="text" id="myName" />
You can simply do this:
<label>Your Name: <input type="text" /></label>
This solves the first issue nicely, but doesn’t do anything about the second — again according to the spec, you’re only allowed to include a single form element within the label. But at least it’s a start.