I am trying to delete checked checkboxes in jQuery, but when i want to get state of checkbox i get error message.
jsfiddle
<div class="control-group">
<label class="checkbox"><input value="0" type="checkbox">Message 0</label>
<label class="checkbox"><input value="1" type="checkbox">Message 1</label>
<label class="checkbox"><input value="2" type="checkbox">Message 2</label>
<label class="checkbox"><input value="3" type="checkbox">Message 3</label>
<label class="checkbox"><input value="4" type="checkbox">Message 4</label>
<label class="checkbox"><input value="5" type="checkbox">Message 5</label>
<label class="checkbox"><input value="6" type="checkbox">Message 6</label>
<label class="checkbox"><input value="7" type="checkbox">Message 7</label>
<label class="checkbox"><input value="8" type="checkbox">Message 8</label>
</div>
<button class="btn" type="button" id="deleteAcc">Delete</button>
My jQuery code is:
$("#deleteAcc").on("click",function(){
$(".control-group label.checkbox").each(function(){
if (this.children(":first").is(':checked')) {
this.remove();
}
});
});
You don't need each
method. Just select the checked inputs and remove the parents (the label elements containing the checkboxes):
$("#deleteAcc").on("click", function() {
$(".checkbox input:checked").parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control-group">
<label class="checkbox">
<input value="0" type="checkbox">Message 0</label>
<label class="checkbox">
<input value="1" type="checkbox">Message 1</label>
<label class="checkbox">
<input value="2" type="checkbox">Message 2</label>
<label class="checkbox">
<input value="3" type="checkbox">Message 3</label>
<label class="checkbox">
<input value="4" type="checkbox">Message 4</label>
<label class="checkbox">
<input value="5" type="checkbox">Message 5</label>
<label class="checkbox">
<input value="6" type="checkbox">Message 6</label>
<label class="checkbox">
<input value="7" type="checkbox">Message 7</label>
<label class="checkbox">
<input value="8" type="checkbox">Message 8</label>
</div>
<button class="btn" type="button" id="deleteAcc">Delete</button>
The actual issue is that the this
context in the $.each
closure is a reference to the DOM node itself. One way you can fix this by wrapping this
in $
:
$("#deleteAcc").on("click",function(){
$(".control-group label.checkbox").each(function(){
if ($(this).children(":first").is(':checked')) {
$(this).remove();
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With