Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML label for name

Is it possible to use the label for attribute for element name instead of id? Our application has a bug where two checkboxes have the same id, and clicking the label for one checks the another. It would be a pain to change the id due the ugly and complicated HTML generation logic.

However, both checkboxes have a unique name-attribute, and it would be a quick solution to use the label for this name. Is this possible?

like image 964
Tuomas Toivonen Avatar asked Jul 22 '26 16:07

Tuomas Toivonen


2 Answers

Is it possible to use label for attribute for element name instead of id?

No.

HTML defines it as relating to the id, only the id, and nothing but the id.

It couldn’t be designed to reference the name because the name is not unique. The problem you are trying to work around is caused by having non-unique ids. The difference with name is that they are allowed (and sometimes required) to be non-unique.

Consider a group of radio buttons. Each one needs a unique <label>, but they have to share a name to make them a group.

like image 145
Quentin Avatar answered Jul 25 '26 06:07

Quentin


You can't bind labels to a name, only an ID. However, you can use labels without using unique IDs.

You can wrap the target element in the label and you won't need the for attribute, like this:

<label><input type="checkbox">Label</label>

Clicking the label will activate the checkbox.

like image 38
roundabout Avatar answered Jul 25 '26 07:07

roundabout