The input name (comment_) must be maximum to 20. It means that If I click 20 times Add comment and remove 5 comments and add 5 again, then should be 16,17,18,19,20 (not 21,22,23,24,25). How I can repair that?
I've tried so far:
var FieldCount = 0;
var x = $("#i_comment").length;
$('#add_comment_box').click(function(e) {
if (x <= 21) {
FieldCount++;
$('#i_comment').append('<div class="in-section-50"><input type="text" class="in-75 mb-20" name="comment_' + FieldCount + '" id="field_' + 0 + '" required/> <a href="#" class="removeclass">Remove comment</a></div>');
x++;
$('#add_comment').show();
$('add_comment_box').html('Add new comment');
if (x == 21) {
$('#add_comment').hide()
}
}
return !1
});
$('body').on('click', '.removeclass', function(e) {
if (x > 1) {
$(this).parent('div').remove();
x--;
$('#add_comment').show();
$('add_comment_box').html('Add new comment')
}
return !1
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='add_comment_box' class='in-section-100'>
<a id='add_comment' class='btn_add_c_a'>Add comment</a>
</div>
<div class='big-section d_b_i' id='i_comment'></div>
FieldCountis not initialized.var x = $("#i_comment").length;is a complicated way forvar x = 1; Ids have to be unique (id="field_' + 0 + '").FieldCountis visible in the console:Uncaught ReferenceError: FieldCount is not defined(just run your code in the snippet). After fixing that problem your code works -> Vote to close as off-topic because this question was caused by a problem that can no longer be reproduced or a simple typographical error.