I need to generate an id in javascript that is guaranteed to be unique. The reason being, I have an app that has multiple tabs. In each of those tabs can be a form that is built dynamically. I want to use labels for the checkboxes in each of those forms, but since it's build dynamically with multiples of the same checkboxes in the dom, I need unique id's for each of them. How can this be accomplished? Or better yet, is there a way to assign the label to a checkbox without needing an id?
Asked
Active
Viewed 2,269 times
0
-
Is the code being built server side (php, etc) or my javascript after page load? – Ben D Mar 02 '12 at 17:00
-
@BenD it's all done by javascript – LordZardeck Mar 02 '12 at 17:04
2 Answers
5
Or better yet, is there a way to assign the label to a checkbox without needing an id?
Yes, you can make the label
element the parent of the input
:
<label>My label: <input type="checkbox"></label>
From the HTML5 spec (emphasis added):
The label represents a caption in a user interface. The caption can be associated with a specific form control, known as the label element's labeled control, either using
for
attribute, or by putting the form control inside thelabel
element itself.
And the HTML 4.01 spec:
To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element.

James Allardice
- 164,175
- 21
- 332
- 312
-
-
alright, that worked! thank you soo much. that problem has plagued me for years, but I always just put up with not having the ability to click the label. I'll accept the answer as soon as it lets me – LordZardeck Mar 02 '12 at 17:03
-
so question: does that mean this won't work in browsers that don't support html-5? – LordZardeck Mar 02 '12 at 17:04
-
@LordZardeck - It is also valid according to the HTML 4 spec (I just linked to the HTML5 spec since that's the one I usually adhere to): http://www.w3.org/TR/html4/interact/forms.html#h-17.9.1 – James Allardice Mar 02 '12 at 17:06
-
alright. I mean, i'd just have to put up with it if not, but I'm glad it does work. – LordZardeck Mar 02 '12 at 17:07
-
@LordZardeck - If it didn't work you would still have the option of using the `for` attribute. But it will definitely work. I've edited the answer with the relevant quote from the HTML 4.01 spec. – James Allardice Mar 02 '12 at 17:08
2
What about using current time as a way of generating unique id?