-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
48 lines (34 loc) · 1004 Bytes
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const inventory = {
apple: { price: 12, qty: 0 },
cherry: { price: 15, qty: 0 },
strawberry: { price: 18, qty: 0 }
}
function sum() {
let total = 0;
const keys = Object.keys(inventory);
keys.forEach(key => {
total += inventory[key].price * inventory[key].qty;
})
return total;
}
function calculate(box) {
let qty = 0;
if (box.value.length > 0) {
qty = parseInt(box.value);
}
inventory[box.id].qty = qty;
const total = sum();
return `$${total}.00`;
}
window.addEventListener('DOMContentLoaded', () => {
const totalContainer = document.getElementById('total-container');
const inputBoxes = document.querySelectorAll('#calculator input');
inputBoxes.forEach(box => {
box.addEventListener('change', () => {
totalContainer.textContent = calculate(box);
});
box.addEventListener('keyup', () => {
totalContainer.textContent = calculate(box);
});
});
});