Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete checked checkboxes in jQuery

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();
        }
    }); 
});
like image 378
Matt Avatar asked Dec 25 '22 02:12

Matt


2 Answers

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>
like image 62
Ionică Bizău Avatar answered Jan 09 '23 19:01

Ionică Bizău


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();
        }
    }); 
});
like image 32
Vinay Avatar answered Jan 09 '23 20:01

Vinay