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

61
Visualizações
Reset Input Value After Unchecking Box Javascript?

Here is my JS code

let items = 0;

document.addEventListener("click", ({ target }) => {
  if (target.className === "food" && target.checked) {
    parseInt(items)
    items += target.value;
    console.log("I clicked the item", items);
  } else if (target.className === "food" && !target.checked) {
    parseInt(items)
    items -= target.value;
    console.log("i unclicked", items);
  })}

HTML Input

 <input type="checkbox" name="item1" value="1000" class="food">
 <input type="checkbox" name="item2" value="2000" class="food">

Right now when I click a checkbox it will add 1000, then when I uncheck it to turns to 2000, then checking again it becomes 3000, and basically just keeps adding them regardless if I check or uncheck

How do I reset the value when I uncheck my input?

Update: I added parseInt and it shows 01000 when I click my checkbox, but when I uncheck it becomes 0. However, if I click 1 checkbox, then another it will add it like 10002000 instead of doing 3000

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

0

I think this is what you are looking for.

let items = 0;

document.addEventListener("click", ({ target }) => {
  if (target.className === "food" && target.checked) {
    items += parseInt(target.value);
    console.log("I clicked the item", items);
  } else if (target.className === "food" && !target.checked) {
    items -= parseInt(target.value);
    console.log("i unclicked", items);
  }})
 <input type="checkbox" name="item1" value="1000" class="food">
 <input type="checkbox" name="item2" value="2000" class="food">

about 4 years ago · Juan Pablo Isaza Relatório

0

Alternatively without the parseInt:

let items = 0;

document.addEventListener("click", ( {target} ) => {
  if (target.className === "food" && target.checked === true) {
    items += +target.value;
    console.log("I clicked the item", items);
  } else if (target.className === "food" && target.checked === false) {
    items -= +target.value;
    console.log("i unclicked", items);
  }});
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