简体   繁体   中英

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? 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.

$(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:

$(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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