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
.
To clone an element and change its id: Use the cloneNode() method to clone the element. Set a different id property on the element. For example, clone.id = 'another-id' .
Well the default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.
To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.
The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).
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" });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With