简体   繁体   中英

How do I prevent this function from modifying the variable more than once?

I wrote this function to modify the text of my HTML tag when a checkbox is marked.

 var price = 15 function checkPrice() { let extraCheese = document.getElementById("extraCheese"); if (extraCheese.checked = true) { price += 5; // console.log(price) document.getElementById('pizzaPrice').innerHTML = `Current Price: $${price}.00` } }
 <input type="checkbox" value="extraCheese" onclick="checkPrice(this);" id="extraCheese" /> <label for="extraCheese"> Extra Cheese </label> <h3 id="pizzaPrice"> Base Price: $15.00 </h3>

It works as intended and adds 5 to the current price, but the checkbox stays checked and each time it is clicked the value adds by five again. What should I do to let the user uncheck the box and reduce the value to what it originally was?

Use else to reduce the price.

There's also no need to call getElementById() , since you pass the element to the function with checkPrice(this)

checked is a boolean property, you don't need to compare it (and you had a typo using = instead of == to compare).

 function checkPrice(extraCheese) { if (extraCheese.checked) { price += 5; } else { price -= 5; } // console.log(price) document.getElementById('pizzaPrice').innerHTML = `Current Price: $${price}.00` }

you can assign an extra property to your element to check if it's already been increased or not

      function checkPrice(extraCheese) {
    var price = 15;

    function checkPrice() {
      let extraCheese = document.getElementById("extraCheese");
      if (
        (extraCheese.checked && (typeof extraCheese.inc == "undefined" || extraCheese.inc == false))
      ) {
        price += 5;
        extraCheese.inc = true;
        // console.log(price)
        document.getElementById("pizzaPrice").innerHTML = `Current Price: $${price}.00`;
      }
    }
  }

You should be watching for the change event of the checkbox, rather than the click event. Then, from the event itself, you can get a handle to the element, and use that to check whether the element is currently checked or not.

Additionally, I recommend keeping your interaction and presentation logic separate. Ie, don't declare event handlers in your HTML, and don't include too much string formatting stuff in your javascript. Keep it surgical, just modify the specific part of the HTML that needs to change -- it will help to wrap the price number in a <span> tag so that you can change the number without having to repeat the 'Base Price: ' part in your javascript. This attention to detail can help keep things clean when your code gets larger.

 var currentPriceElement = document.getElementById('currentPrice'); function getCurrentPrice() { return Number(currentPriceElement.textContent); } function setCurrentPrice(price) { currentPriceElement.textContent = price.toFixed(2); } function onExtraCheeseChange(event) { var target = event.target; var price = getCurrentPrice(); if (target.checked) { price += 5; } else { price -= 5; } setCurrentPrice(price); } document.getElementById('extraCheese').addEventListener('change', onExtraCheeseChange);
 <input type="checkbox" value="extraCheese" id="extraCheese" /> <label for="extraCheese"> Extra Cheese </label> <h3 id="pizzaPrice"> Base Price: $<span id="currentPrice">15.00</span> </h3>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM