Alex Anderson
Alex Anderson

Reputation: 153

Removing dynamic form elements jQuery

I am currently using jQuery to add dynamic form elements to my webpage. After each form element is added I want the user to be able to remove that element if necessary. I currently try and do this using jQuery, I am attempting to target certain classes and remove them, however at the moment nothing is happening and there aren't any errors in my console.

Here is my remove code and here is a JS fiddle I have made.

$(document).on('click', '.ingredient .remove', function () {
    $(this).parents('.ingredient .quantities').remove();
    return false;
});

https://jsfiddle.net/zp9faa2h/

Upvotes: 1

Views: 64

Answers (1)

BenG
BenG

Reputation: 15154

The .ingredient and .quantities have different parents. Thats why .parents('.ingredient .quantities') returns nothing to remove.

it would be best to wrap both these in a parent div, but you could do it like the following:-

$(document).on('click', '.ingredient .remove', function () {
     $(this).closest('.ingredient').parent().next().remove();
     $(this).closest('.ingredient').parent().remove();
     return false;
});

This then finds the closest .ingredient goes up to the parent and removes the next container .quantities. then removes the parent of .ingredients.

Fiddle

Upvotes: 1

Related Questions