Adding And Removing Input Fields With Jquery
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 pr
Solution 1:
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
jQuery(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++;
}
});
$('#inp').on('click', '.remove_field', function (e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><buttonid="add">Add</button><divid="inp"></div>
Problem: Demo
Solution 2:
Here is a small example, See this link
http://jsfiddle.net/vh3Js/
Hope this will help you.
HTML :
<formid="myForm"><divstyle="margin-bottom:4px;"class="clonedInput"><inputtype="button"class="btnDel"value="Delete"disabled="disabled" /><inputtype="text"name="input1" /></div><div><inputtype="button"id="btnAdd"value="add another name" /></div></form>
JS:
$(document).ready(function() {
var inputs = 1;
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name','input'+ (++inputs) );
$('.clonedInput:last').after(c);
});
$('.btnDel').click(function() {
if (confirm('continue delete?')) {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel').attr('disabled',($('.clonedInput').length < 2));
}
});
});
Post a Comment for "Adding And Removing Input Fields With Jquery"