'jQuery remove element with next() and remove()
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 class="steps-row-first">
<div class="form-group">
<div class="radio-wrapper">
<div class="radio-group">
<input type="radio" class="anotherCheese" name="anotherCheese" value="yes">
<label>Yes</label>
</div>
<div class="radio-group">
<input type="radio" class="anotherCheese" name="anotherCheese" value="no">
<label>No</label>
</div>
</div>
</div>
<div style="clear:both;"></div>
<div class="added"></div>
</div>
When I click the no radio button the element does not get removed, what am I doing wrong ?
Solution 1:[1]
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();
Solution 2:[2]
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();
}
....
Solution 3:[3]
$(".steps-row-first").on("change", ".anotherCheese", function() {
if($(this).val() == 'no') {
$(".steps-row-first").find(".added").remove();
}
else
{
$(".steps-row-first").append("<div class='added'></div>");
}
});
you can use find() to find all class .added and remove it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Spring |
| Solution 3 | Long Chu Hai |
