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>