Home > database >  Remove Event Listener from Checkbox Using Input Type?
Remove Event Listener from Checkbox Using Input Type?

Time:06-03

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

CodePudding user response:

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)}`;
});

CodePudding user response:

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.

CodePudding user response:

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

  • Related