Home > database >  Reset Input Value After Unchecking Box Javascript?
Reset Input Value After Unchecking Box Javascript?

Time:06-05

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" >
 <input type="checkbox" name="item2" value="2000" >

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

CodePudding user response:

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" >
 <input type="checkbox" name="item2" value="2000" >

CodePudding user response:

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);
  }});
  • Related