Reputation: 10302
I want to clone one row of a table, but when I clone, the new element's name
and id
will be the same as the element from which it was cloned.
What I need is the cloned elements with a different name
and id
.
Upvotes: 13
Views: 26379
Reputation: 134
You can automate your clone with cloneJS. It's just a beta version: CloneJS
Upvotes: 0
Reputation: 126052
I would pass prop
a map of key/value pairs to update these values after cloning:
$("#selector").clone().prop({ id: "newId", name: "newName"});
Cloned elements don't exist in the DOM until you add them, so you're not going to have to worry about duplicate id
s until you do that.
Example: http://jsfiddle.net/BbpRA/
Update: In the comment you say you have 20 input
s you need to clone. I would create a function that takes the DOM element and the new id and name. You could even make a small plugin out of it:
(function($) {
$.fn.cloneWithProperties = function (properties) {
return this.clone().prop(properties);
};
})(jQuery)
Usage:
$("#selector").cloneWithProperties({ id: "newId", name: "newName" });
Upvotes: 32
Reputation: 66663
You can do something like:
var x = $("#selector").clone();
x.find('#oldID1').attr({id: "newID1", name: "newName1"});
x.find('#oldID2').attr({id: "newID2", name: "newName2"});
...
Once its done, you can append x to wherever you want.
Pls note that the #selector above refers to your table row element.
Upvotes: 2
Reputation: 8770
You could try something like this:
<div class="container">
<div class="goodbye">
Goodbye
<div id="h1" class="hello">Hello</div>
</div>
</div>
$('#h1').clone().attr('id','h2').appendTo('.container');
Upvotes: 6