Adding and removing input fields with jquery

2019-09-10 03:18发布

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--;   
        });
    });
});

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-10 03:57

Here is a small example, See this link

http://jsfiddle.net/vh3Js/

Hope this will help you.

HTML :

<form id="myForm">
    <div style="margin-bottom:4px;" class="clonedInput">
        <input type="button" class="btnDel" value="Delete" disabled="disabled" />
        <input type="text" name="input1" />
    </div>

    <div>
        <input type="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));
        }
    });


});
查看更多
等我变得足够好
3楼-- · 2019-09-10 03:59

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--;
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="add">Add</button>
<div id="inp"></div>

Problem: Demo

查看更多
登录 后发表回答