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?
2 Answers
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
forattribute, or by putting the form control inside thelabelelement 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.
6 Comments
What about using current time as a way of generating unique id?