-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
91 lines (79 loc) · 2.04 KB
/
script.js
File metadata and controls
91 lines (79 loc) · 2.04 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const items = [{
name: 'Pizza ',
price: 5.9,
quantity:1
},
{
name: 'Đùi gà',
price: 6.9,
quantity:1
},
{
name: 'Cánh gà',
price: 7.9,
quantity:1
}
]
const SHIPPING = 2;
function add(){
items.push({
// name: `Nước ngọt ${Math.random().toFixed(2)}`,
name: `Nước ngọt ${Math.random().toFixed(2)}`,
quantity: 1,
price: Math.random()*10
})
render();
}
function remove(index) {
items.splice(index, 1)
render();
}
function updateQuantity(index, quantity) {
if(quantity < 1){
return
}
items[index].quantity = quantity
render();
}
function render(){
let subTotal = 0;
items.forEach(item => {
subTotal += item.quantity * item.price
})
const total =subTotal + SHIPPING;
const html = items.map(item => `
<li class="order-item">
<span class="item-name">${item.name}</span>
<span class="item-quantity">
<button class="dec">-</button>
<input type="number" class="quantity" value="${item.quantity}" />
<button class="inc">+</button>
</span>
<span class="item-price">
<span>$${(item.quantity * item.price).toFixed(2) }</span>
<button class ="delete btn-delete">X</button>
</span>
</li>`).join('')
$('#order-items').innerHTML = html
const deleteButtons = [...$$('.delete')]
const decButtons = [...$$('.dec')]
const incButtons = [...$$('.inc')]
for(let i = 0; i < deleteButtons.length; i++) {
decButtons[i].addEventListener('click', () => {
updateQuantity(i, items[i].quantity - 1)
})
incButtons[i].addEventListener('click', () => {
updateQuantity(i, items[i].quantity + 1)
})
deleteButtons[i].addEventListener('click', () => {
remove(i);
})
}
$('#sub-total').innerText = `$${subTotal.toFixed(2)}`
$('#shipping').innerText = `$${SHIPPING}`
$('#total').innerText = `$${total.toFixed(2)}`
}
$('#btn-add').addEventListener('click', () => {
add();
})
render();