jQuery - Clone html and increment id of some elements
HTML
<div id="clonedInput1" class="clonedInput">
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
CSS
.centeralign {
text-align: center;
}
borderalign{
background-color: black;
width: 300px;
padding: 18px;
margin: 400px;
border-radius: 10px;
}
button{
height: 50px;
width: 70px;
}
JavaScript
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);