ed209
ed209

Reputation: 838

Jquery remove button stops working after one click

I have a form which allows users to dynamically add fields. Every field after the first has a "remove" button added to it.
The following is in the document.ready

var new_button =$('<div class="form-actions"><button type="button" class="btn btn-primary remove pull-right">Remove</button></div>').click(function(){
    $(this).parents('.field_group').remove();
    });

I then append the button to the new group of fields when they are created like this

$('#more_fields').click(function(){
    $('.field_group:first').clone(true).insertAfter('.field_group:last');
        var last = $('.field_group:last');
        last.append(new_button);
 );

My goal is to remove the entire ".field_group" that surrounds the button each time it is clicked. However, this only works once. Oddly enough if I have the button do something else like change the field group background color it works all the time.

Upvotes: 1

Views: 248

Answers (2)

krishwader
krishwader

Reputation: 11371

For a more modular approach which doesn't involve loads of HTML, you could change new_button to the following :

var new_button = $("<div/>", {
    "class": "form-actions"
}).append($("<button/>", {
    "class": "btn btn-primary remove pull-right",
    "text": "Remove"
})).on("click", "button", function () {
     $(this).parents('.field_group').remove();
});

and as Darhazer mentioned, you must use clone(true).

$('#more_fields').click(function(){
    $('.field_group:first').clone(true).insertAfter('.field_group:last');
        var last = $('.field_group:last');
        last.append(new_button.clone(true));

});

Upvotes: 2

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

You have to append a copy of the button.

last.append(new_button.clone(true));

Upvotes: 2

Related Questions