You can reconsider your code, just define a model div to use to clone the new rows when you click add rows.
The model div is used only for the cloning and is always hidden. The remove button remove the cloned div so the add always work.
At the end the code looks more simple too.
Code:
<div class='container'>
</div>
<div class="test">Add person</div>
<div class='model_container'>
<div class="model_loop"> <strong>Person 1</strong>
<br/>
<input type="text" name="first name" />
<input type="text" name="lastname" />
<input type="text" name="mail" />
<input type="text" name="company" />
<div class="remove">remove</div>
</div>
</div>
jQuery:
$(document).ready(function () {
clicks = 0;
$('div.test').on('click', function () {
$('.attnd2').show();
if ($('div.loop').length < 5) {
clicks++;
newLoopDiv = $($('div.model_loop')[0]).clone().appendTo(".container").removeClass("model_loop").addClass("loop").show();
$('input', newLoopDiv).each(function (index, element) {
$(element).attr('name', $(element).attr('name') + clicks);
});
}
$(".remove").click(function () {
$(this).closest('.loop').remove();
});
});
$(".remove").click(function () {
$(this).closest('.loop').remove();
});
});
Demo: http://jsfiddle.net/8JQrj/10/
EDIT
You also need to renum the name of the remaing div after a remove.
I suggest you to don't use the name attribute and parse it to remove the index, but a custom data attribute data-progr
.
Inserted the remove action as one function using on
.
Code:
$(document).ready(function () {
clicks = 0;
$('div.test').on('click', function () {
$('.attnd2').show();
if ($('div.loop').length < 5) {
clicks++;
newLoopDiv = $($('div.model_loop')[0]).clone().appendTo(".container").removeClass("model_loop").addClass("loop").show();
$('input', newLoopDiv).each(function (index, element) {
$(element).attr("data-progr", clicks);
});
}
});
$("body").on('click','.remove', function () {
$(this).closest('.loop').remove();
clicks--;
$('.loop').each(function (indexdiv, eldiv) {
$('input', eldiv).each(function (index, element) {
console.log(indexdiv)
$(element).attr("data-progr", indexdiv);
});
});
});
});