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

112
Visualizações
Remove Event Listener from Checkbox Using Input Type?

So I have this simple event listener that updates my price when I click on a checkbox.

However, I don't see how I can refactor my logic to make it subtract the price after unchecking a check box?

let items = 0;

document.addEventListener("click", (e) => {
  if (e.target.matches("input[type=checkbox]")) {
    items += +e.target.value;
    console.log(items);

    document.getElementById("price").textContent = `Food Total: $${(
      items / 100
    ).toFixed(2)}`;
  }
});

So far this code adds all my checkboxes values, but if I continue to click and unclick them, they still add the value to infinity

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Maybe you can add a class "checked" when clicking the checkbox and remove it when clicking again? Then you could work with the class instead of the raw click event.

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd add the checked boxes to a Set and add/delete them from the Set on click. Check whether they're already in the set to determine whether you need to add or subtract from the sum.

const clickedCheckboxes = new Set();
let sum = 0;
const priceDiv = document.getElementById("price");
document.addEventListener("click", ({ target }) => {
    if (!target.matches("input[type=checkbox]")) {
        return;
    }
    if (clickedCheckboxes.has(target)) {
        clickedCheckboxes.delete(target);
        sum -= target.value;
    } else {
        clickedCheckboxes.add(target);
        sum += Number(target.value);
    }
    priceDiv.textContent = `Food Total: $${(sum / 100).toFixed(2)}`;
});
about 4 years ago · Juan Pablo Isaza Relatório

0

I think checkboxes should have a simple boolean value of .checked being either true or false: https://www.w3schools.com/jsref/prop_checkbox_checked.asp

That might allow you to decrement if .checked === false

about 4 years ago · Juan Pablo Isaza 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