简体   繁体   中英

jQuery Remove Parent Fieldset

I have a form that has multiple instances of the same field set. You can add more field sets by clicking "Add a Field."

The page starts with 5 field sets. If you click "Remove," the background color will change to red (so that you can tell which field set would be removed).

If you add more fields, those field sets will not respond to the "Remove" button even though they have the exact same code as the ones that the page starts out with, and they are added to the same form.

Can you please take a look at my code and let me know why the added fields will not remove whereas the ones that start out on the page remove?

https://jsfiddle.net/Lc510xmn/1/

// Adds a new field set to the form

$('[data-action="addField"]').click(function(){
        var fieldSet = '<fieldset><input type="text" name="field"><button type="button" data-action="removeField">Remove</button></fieldset>';
        $('form').append(fieldSet);
  return false;
});

// Changes the background to red instead of removing

$('[data-action="removeField"]').click(function(){
    $(this).parents('fieldset').css('background-color','red');
return false;
});

The bound events doesn't work for dynamically added/created elements, so you need to delegate the event to very first parent that will not be manipulate dynamically (using jQuery or JavaScript ).

From jQuery documentation :

// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );

Also you can read Event binding on dynamically created elements .


So you should change your code like this:

// jQuery 1.7+
$('form').on('click', '[data-action="removeField"]', function() {
    $(this).parents('fieldset').css('background-color', 'red');
    return false;
});

Updated js fiddle is here https://jsfiddle.net/Lc510xmn/2/

$(function(){

    $('[data-action="addField"]').click(function(){
            var fieldSet = '<fieldset><input type="text" name="field"><button type="button" data-action="removeField">Remove</button></fieldset>';
            $('form').append(fieldSet);
      return false;
    });

    $("#fields").on("click", '[data-action="removeField"]', function(event){
        $(this).parents('fieldset').css('background-color','red');
    return false;
    });

});

试试这个$(this).parents('fieldset').remove()

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