jQuery - Clone html and increment id of some elements
HTML
<div class="container">
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
<select class="" name="txtCategory[]" id="category2">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
</div>
CSS
body { padding: 10px;}
.clonedInput { padding: 10px; border-radius: 5px; background-color: #def; margin-bottom: 10px; }
.clonedInput div { margin: 5px; }
JavaScript
// forked from: http://jsfiddle.net/mjaric/tfFLt/
var regex = /^(.*)(\d)+$/i,
cloneIndex = $(".clonedInput").length;
(function($) {
$('.container').on('click', 'button.clone', function(e){
e.preventDefault();
$(this).parents('.clonedInput').clone()
.appendTo('.container')
.attr('id', 'clonedInput' + cloneIndex)
.find('*').each(function(){
var id = this.id || '',
match = id.match(regex) || [];
if (match.length === 3) {
this.id = match[1] + (cloneIndex);
}
});
cloneIndex++;
});
$('.container').on('click', 'button.remove', function(e){
e.preventDefault();
console.log($(this).parents('.clonedInput'));
$(this).parents('.clonedInput').remove();
});
})(jQuery);