使用jQuery添加和删除输入字段 [英] Adding and removing input fields with jquery

查看:78
本文介绍了使用jQuery添加和删除输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery添加输入字段时遇到问题.

I have a problem while adding input fields with jQuery.

我将限制设置为5个输入字段.但是,如果我尝试删除输入字段,则我的限制无效. 当我使用x--时,我的var x是不适当的减量,例如,如果我有5个输入字段,并且当我单击以删除一个输入时,var x是-4而不是-1.

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

推荐答案

问题是您正在将添加处理程序添加到添加处理程序中,而不是使用

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>

问题:演示

这篇关于使用jQuery添加和删除输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆