Nikki Erwin Ramirez
Nikki Erwin Ramirez

Reputation: 9964

Is there a way to make HTML labels work with form elements without IDs?

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.

Upvotes: 2

Views: 713

Answers (3)

grossvogel
grossvogel

Reputation: 6782

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.

Upvotes: 0

Kobi
Kobi

Reputation: 138147

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.

Upvotes: 11

Nikki Erwin Ramirez
Nikki Erwin Ramirez

Reputation: 9964

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="" />

Upvotes: 1

Related Questions