I was trying to code a POS like system as a small project to learn with. So currently I have two buttons "cola" and "fanta". The prices of those drinks are in an object. As soon as I click on one button the price needs to be added to sum. Well what the code is currently doing is to add up the prices of the same product. So if I click three times in a row on "cola", which has a price of 3, I get 9 as sum. So far so good, but as soon as I click fanta, which has a price of 2, I get a sum of 2. But when I continue with the cola button it continues at 12 and so on.
Here is the code:
const btnChoose = document.querySelectorAll(".btn");
const drinks= {
cola: 4,
fanta: 3,
};
for (let i = 0; i < btnChoose.length; i++) {
let sum = null;
btnChoose[i].addEventListener("click", function () {
let price = drinks[this.id];
sum += price;
console.log(typeof sum, sum);
});
}
and here is the HTML:
<!DOCTYPE html>
<html>
<head>
<title>POS</title>
</head>
<body>
<button class="btn" id="cola">Cola</button>
<button class="btn" id="fanta">Fanta</button>
<script>
....
</script>
</body>
</html>