0

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
  • Is the code being built server side (php, etc) or my javascript after page load? Commented Mar 2, 2012 at 17:00
  • @BenD it's all done by javascript Commented Mar 2, 2012 at 17:04

2 Answers 2

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 the label 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.

Sign up to request clarification or add additional context in comments.

6 Comments

really?? i didn't know that! lemme try that real quick
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
so question: does that mean this won't work in browsers that don't support html-5?
@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): w3.org/TR/html4/interact/forms.html#h-17.9.1
alright. I mean, i'd just have to put up with it if not, but I'm glad it does work.
|
2

What about using current time as a way of generating unique id?

Create a unique number with javascript time

1 Comment

While i prefer to use James' method, this is a good answer also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.