I am using jQuery to remove an element with the class named "added
" There are multiple elements with this class name.
$(".steps-row-first").on("change", ".anotherCheese", function() {
if($(this).val() == 'no') {
$(this).parent().next(".added").remove();
}
else
{
$(".steps-row-first").append("<div class='added'></div>");
}
});
Here is the HTML:
<div >
<div >
<div >
<div >
<input type="radio" name="anotherCheese" value="yes">
<label>Yes</label>
</div>
<div >
<input type="radio" name="anotherCheese" value="no">
<label>No</label>
</div>
</div>
</div>
<div style="clear:both;"></div>
<div ></div>
</div>
When I click the no radio button the element does not get removed, what am I doing wrong ?
CodePudding user response:
Your jQuery is wrong for removing the element. In $(this).parent().next(".added").remove();
, $(this)
is the input element, so it's parent is just the .radio-group
element. You need to change it to $(this).parents('.radio-wrapper').next(".added").remove();
Even above will not work because there is a <div>
between .radio-wrapper
and .added
, to make it work, you need to use next()
twice: $(this).parents('.radio-wrapper').next().next(".added").remove();
CodePudding user response:
I dont know , where what's exactly the .steps-row-first
the element
but try using parents to get back then chose the parent's siblings to target your div with added class as below:
....
if($(this).val() == 'no') {
$(this).parents(".form-group").siblings(".added").remove();
}
....