I have a problem while adding input fields with jQuery.
I set limit to 5 input fields. But if i try to remove input fields, my limit dont work . My var x when i use x-- is not proper decrement, for example if i have 5 input fields and when i click to remove one input , var x is -4 instead -1.
Can someone help me to solve this problem. My code is:
$('document').ready(function() {
var max = 5;
var x = 0;
$('#add').click(function(e) {
if(x < max) {
$('#inp').append('<div><input class = "new_input" type=text name="name[]" placeholder="Unesite podatak"/><a class="remove_field "href="#"> X</a><div><br/>');
x++;
}
$('.remove_field').click( function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
});
Here is a small example, See this link
Hope this will help you.
HTML :
JS:
The problem is you are adding the remove handler inside the add handler instead of using event delegation. So the previously added remove elements will get multiple remove handlers causing x to be decremented multiple times
Problem: Demo