Reputation: 5598
How do I give an unique NAME or other ATTR to a element that is cloned?
Thank you in advance.
Upvotes: 0
Views: 464
Reputation: 11
Use Math.random:
$('.some_element').each(function() {
var id = (Math.floor(Math.random()*10000000000000000));
$(this).clone().attr('id', id);
});
Or, if you'd like a "handle" on the original element, you could create a new id in this format:
ORIGINAL_ELEMENT_ID + SEPARATOR + RANDOM_NUMBER
E.g.,
$('.some_element').each(function() {
var id = [
this.id,
(Math.floor(Math.random()*10000000000000000))
].join('-');
$(this).clone().attr('id', id);
});
Upvotes: 1
Reputation: 905
A hack-ish way to do this would be to use a global counter and keep incrementing it by One before adding the value to the name of the cloned element.
ex.
var count =1;
func some_func() {
var cloneElement = $(form).clone();
cloneElement.attr('name', cloneElement.attr('name') + count++);
}
Upvotes: 0