How to get current data of elements while cloning using jquery. While cloning, it's copy's only the default data in the elements.
Here is the code
souRce.clone()
.prop('id', newName)
.html(function () {
return $(this).html().replace(RegExp(PrevID, 'g'), newName);
})
.appendTo(DestiNation);
The problem is, instead of using the cloned element, you are changing its content with the raw html which will replace runtime content with original html markup
So instead of replacing the entire html, just update the id
and name
properties like
var counter = 1;
function clone() {
var souRce = $('.item').eq(0),
DestiNation = $('#ct'),
PrevID = 'item-' + counter,
newName = 'item-' + ++counter;
var regex = RegExp(PrevID, 'g');
souRce.clone()
.prop('id', newName)
.find('[id], [name]').each(function() {
if (this.id) {
this.id = this.id.replace(regex, newName);
}
if (this.name) {
this.name = this.name.replace(regex, newName);
}
}).end()
.appendTo(DestiNation);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ct">
<div class="item" id="item-1">
<input name="a" value="A" id="a-item-1" />
<input name="b" value="B" id="b-item-1" />
<input name="c-item-1" value="C" id="c-item-1" />
</div>
</div>
<button onclick="clone()">Clone</button>