简体   繁体   English

如何动态添加和删除多个字段?

[英]How to dynamically add and remove fields for more than one?

Is there an easier way in JQuery to dynamically add and remove fields for more than one field within the same form? 在JQuery中,有没有一种更简便的方法可以动态添加和删除同一表单中多个字段的字段? I have two form elements in the same form that I'd like to have the ability to add and remove blank fields to. 我有两个表单元素,它们具有与我想添加和删除空白字段相同的能力。

<div class="col-sm-3">
    Email<g:field type="email" name="Email" class="form-control" required="" value="" aria-labelledby="Email-label"/>
</div>
<div class="col-sm-2">  
    Fax<g:field type="tel" name="Fax" class="form-control" required="true" value="" aria-labelledby="Fax-label"/>
</div>

I have cobbled together this javascript piece from several different places and it works just fine for the first field, but when I try to duplicate it for the second one it doesn't work. 我已经从几个不同的地方拼凑了这个javascript片段,它在第一个字段中工作得很好,但是当我尝试在第二个字段中复制它时,它是行不通的。

$(document).ready(function(){
    $("#add").click(function (e) {
        $("#submitterEmail").append('<div><input type="text" name="submitterEmail[]"><button class="delete">Delete</button></div>');
    });

$("body").on("click", ".delete", function (e) {
    $(this).parent("div").remove();
});
});

Here's the JavaScript based on the HTML you have: 这是基于您拥有的HTML的JavaScript:

$(document).ready(function(){
    $("#add").on("click", function(){
        $("#container").append(
            "<div class='col-sm-3'><g:field>Another field <button class='delete'>Delete</button></div>"
        );
    });
    $(document).on("click", ".delete", function(){
        $(this).parent().parent().remove();
    });
});

Example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM