Aaron Aaron - 1 year ago 102
jQuery Question

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?


// Adds a new field set to the form

var fieldSet = '<fieldset><input type="text" name="field"><button type="button" data-action="removeField">Remove</button></fieldset>';
return false;

// Changes the background to red instead of removing

return false;

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download