Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple elements if checkbox is checked using javascript?

Tags:

javascript

So I got this code, I figured out how to delete one element with the checkbox checked but if I try to delete the second div it won't let me? Does anyone have a solution to it?

HTML

<div id="product-space">
            <div id="product"> <input type="checkbox" id="delete-checkbox">
                <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
            </div>
            <div id="product"> <input type="checkbox" id="delete-checkbox">
                <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
            </div>
        </div>
<button type="submit" name="button" value="enter" id="button" onclick="removeCheckedCheckboxes()">MASS DELETE</button>

JavaScript

function removeCheckedCheckboxes() {
    var checkBox = document.getElementById("delete-checkbox");
    var box = document.getElementById("product");
    if (checkBox.checked == true) {
        box.style.display = "none";
    }
}
like image 676
gonoff Avatar asked Apr 25 '26 15:04

gonoff


1 Answers

The reason your code does not work is because you use the id attribute multiple times with the same value. This is against HTML standards. Also you use getElementById which can only return a single element.

I would suggest using css classes for marking all relevant elements, and using a simple CSS selector for matching all checked boxes.

function removeCheckedCheckboxes() {
  var checked = document.querySelectorAll(".delete-checkbox:checked");
  checked.forEach((elem) => {
    elem.parentElement.style.display = "none";
  })
}
<div id="product-space">
  <div class="product"> <input type="checkbox" class="delete-checkbox">
    <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
  <div class="product"> <input type="checkbox" class="delete-checkbox">
    <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
</div>
<button type="submit" name="button" value="enter" id="deleteButton" onclick="removeCheckedCheckboxes()">MASS DELETE</button>
like image 134
Hubert Grzeskowiak Avatar answered Apr 27 '26 04:04

Hubert Grzeskowiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!