Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

536
Visualizações
How to delete multiple elements if checkbox is checked using 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";
    }
}
over 4 years ago · Santiago Trujillo
4 Respostas
Responde à pergunta

0

see the ref:

getElementById will return the first element with the given ID

You could name them as different ids if just want to handle this issue quickly.

over 4 years ago · Santiago Trujillo Relatório

0

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>

over 4 years ago · Santiago Trujillo Relatório

0

Document.getElementById() is used to find elements from DOM with matching ID. It returns a single Element object representing the element whose id property matches the specified string. In your case you have multiple elements with same id. So it will always returns the first element while running this script. So your second element remains in visible state always.

So a better approach is to pick the element using class name rather than id, because id is supposed to be unique and class names need not be unique.

Logic

  • Pick the target elements using the class names. I used same class names product for the container div and delete-checkbox for the check boxes.
  • On clicking delete button, loop through the elements with class name product.
  • Find checkbox inside each product element by checking an element with classname delete-checkbox inside each node.
  • Check the checked status of each checkbox, if checked, hide the box.

Working Fiddle

var boxes = document.querySelectorAll(".product");
function removeCheckedCheckboxes() {
    boxes.forEach((box) => {
        const checkBox = box.querySelector('.delete-checkbox');
        if (checkBox.checked == true) {
            box.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="button"
    onclick="removeCheckedCheckboxes()">MASS
    DELETE
</button>

over 4 years ago · Santiago Trujillo Relatório

0

the first thing is, both of your items have the same ID, and you must never use the same ID for multiple divs's. When you use document.getElementById, you return only the first object, and you are not exactly deleting the code by clicking in your button. Try get your element by a class or a tagName like those input fields of yours.

function removeCheckedCheckboxes() {
  var list = document.getElementsByTagName('input')
  for (var i = 0; i < list.length; ++i) {
    var product = list[i]
    if (product.checked)
      product.parentElement.hidden = true
  }
}
<div id="product-space">
  <div class="product">
    <input type="checkbox">
    <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
  <div class="product">
    <input type="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>

https://www.quora.com/Is-it-ever-ok-to-use-the-same-ID-for-multiple-elements-in-HTML-Doesnt-CSS-specificity-make-IDs-more-granular-than-classes-Doesnt-this-violate-the-rules-of-HTML-Is-there-ever-a-reason-to-do-this

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda