Output won't update as expected when checking a checkbox

Hi everyone!
I’m going through Beginners JavaScript 5th Edition by Jeremy McPeak.
I’m doing an exercise that involves building an interface for users to “build” their ideal computer and the price should uodate as they add/remove components.
I’m getting there, but I have a problem with my checkboxes. I currently have two checkboxes, one for BluRay and one for DVD-ROM, and they worked perfectly with the exception that the value I want to add with them to the final price doesn’t get substracted when unchecking them, but when I add an else statement that covers the case when the element is unchecked, only the last checkboxs behaves as expected. Here’s the relevant section:

        var compSpec = "Your chosen processor speed is ";
        var numberOfControls = myForm.length;
        var newPriceWithComps = newPrice;

      function additionalComp() {
        for (var index = 0; index < numberOfControls; index++) {
          var element = myForm[index];
          if (element.type == "checkbox") {
            if (element.checked) {
              compSpec = compSpec + element.value + "\n";
              if (element.value == "DVD-ROM") {
                newPriceWithComps = newPrice + 48;
                outputprice.innerHTML = newPriceWithComps;
              }
              if (element.value == "Blu-ray") {
                newPriceWithComps = newPrice + 64;
                outputprice.innerHTML = newPriceWithComps;
              }
            }
            else {
                  outputprice.innerHTML = newPrice;
              }
            }
          }
        }

Thanks in advance for your help!!

Cheers.

I’m not familiar with this excercist, but here you set the default to newPrice if the !!element.checked (the double !! is just a way to make it explicit that we’re checking for the value to exist.

Which accounts for if the item is checked. But I don’t see a way to check if the item has been toggled. So what happens if the item was checked, but now is not checked?

Thanks for your reply :slight_smile:

That’s why I put the else statement there, but it only workd for the last item :thinking:

Any suggestions ?

I don’t know your current data structures, but my first instinct would be to use a prop to track if the item has been added to the total price. Then the logic would be like this in pseudo code

// handle first time in cart
if !!element.checked && !element.inCart
  add item to cart
  toggle inCart (set true)

...
// handle item was removed from cart
else if 
/* !! is just an explicit check for truthiness */
  !element.checked && !!element.inCart
    deduct price from cart
    toggle inCart (set false)