tags:

views:

37

answers:

3

For example, given:

<label for="username">Username:</label>
<input id="username" name="username" value="" />

When you click on the "Username:" label, focus goes to the corresponding form field.

Without resorting to JavaScript, is it possible to have the same behavior when the form field has no ID?

Real world example where this will be an issue is for dynamically constructed forms, where you may add similar fields to a form, or maybe add multiple instances of the same form.

A: 

The solution I'm considering is appending something to the ID to make it unique. For example, the timestamp:

<label for="username-12019734517">Username:</label>
<input id="username-12019734517" name="username" value="" />
Nikki Erwin Ramirez
You should add this to your question (and delete it as an answer) instead. Use the edit link under the question to update it.
tvanfosson
But isn't this an answer by itself?
Nikki Erwin Ramirez
+9  A: 

Yes, the label is associated implicitly with the first input it conatins:

<label>Username:
<input name="username" value="" />
</label>

From the W3:

To associate a label with another control implicitly, the control element must be within the contents of the LABEL element

In fact, I consider nesting the input in the label better-practice; it can be more semantic, and in some cases leads to a better ui, by eliminating non-clickable spaces between radio buttons or check-boxes and their labels.

Kobi
This is just great! Thanks! :)
Nikki Erwin Ramirez
A: 

I would be surprised if there's a true answer to your question, but I'll wait and see. A workaround would be to construct the ids programmatically. So if you have a form that you're going to duplicate, give each instance its own name and id like form0, form1, and its inputs ids like form0_username, etc.

grossvogel