1

I have a problem with the total price of a cart. Theoretically, the function should update the total whenever I press the "buy" button, but it just replaces the price.

Instead of doing 0 + price + price + price +..., it does 0 + price, then again 0 + price.

How can I fix it?

function buy(id) {

  var total = 0;
  for (var i in albums) {
    if (albums[i].id == id) {
      if (albums[i].quantity > 0) {
        albums[i].quantity--;
        total += albums[i].price;
      }
    }
  }


  for (var i in singles) {
    if (singles[i].id == id) {
      if (singles[i].quantity > 0) {
        singles[i].quantity--;
        total += singles[i].price;
      }
    }
  }

  for (var i in soundtracks) {
    if (soundtracks[i].id == id) {
      if (soundtracks[i].quantity > 0) {
        soundtracks[i].quantity--;
        total += soundtracks[i].price;
      }
    }
  }

  document.getElementById('purchases').innerHTML = total;
}
<button onClick='buy("+this.id+")'>Buy</button>
pushkin
  • 9,575
  • 15
  • 51
  • 95
Sirius094
  • 41
  • 4

2 Answers2

2

Everytime time you do a button click, you are calling yourbuy function. In that function you are declaring var total = 0. Thats why it always starts with 0. You should declare your total not with 0 but with previous number. In your case, that would be from document.getElementById('purchases').innerHTML. So total = document.getElementById('purchases').innerHTML, or move var total = 0 outside of function.

Sagi
  • 191
  • 13
0

I moved the total out as others pointed out, but I also made some refactors to remove repeated logic.

//moved the total outside of the method so it is not reinitialized
//as others have already mentioned
var total = 0;

//also reduced your repeated logic
function totalElements (elements, id) {
  elements.forEach(function(element){
    if (element.id == id && element.quantity > 0) {
      element.quantity--;
      total += element.price;
    }
  });
}

function buy(id) {
  totalElements(albums, id);
  totalElements(singles, id);
  totalElements(soundtracks, id);

  document.getElementById('purchases').innerHTML = total;
}
<button onClick='buy("+this.id+")'>Buy</button>
Taplar
  • 24,788
  • 4
  • 22
  • 35