-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcart.js
62 lines (55 loc) · 2.31 KB
/
cart.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
window.onload = () => {
let cart = [];
if (localStorage.getItem("cart"))
cart = JSON.parse(localStorage.getItem("cart"));
update_cart();
//Cart and change quantity and remove item
function update_cart() {
//Already mentioned in cart.html
const cartitems = document.getElementById("cart_items");
const totalprice = document.getElementById("total_price");
cartitems.innerHTML = "";
let total = 0;
localStorage.setItem("cart", JSON.stringify(cart));
cart.forEach((item, index) => {
cartitems.innerHTML += `<tr class="cart_items">
<td>${index + 1}.</td>
<td class="name">${item.name}</td>
<td><button class="change" index=${index} operator="-">-</button></td>
<td class="quantity">${item.quantity}</td>
<td><button class="change" index=${index} operator="+">+</button></td>
<td class="price">         ${
item.price * item.quantity
}      </td>
<td><button class="remove" index=${index}>Remove<button></td>
</tr>`;
total = total + item.price * item.quantity;
});
totalprice.textContent = total;
const change_button = document.getElementsByClassName("change");
[...change_button].forEach((button) => {
button.addEventListener("click", function () {
const index = this.getAttribute("index");
const operator = this.getAttribute("operator");
if (operator === "+") {
cart[index].quantity++;
} else if (operator === "-" && cart[index].quantity >= 1) {
if (cart[index].quantity == 1) {
cart.splice(index, 1);
} else {
cart[index].quantity--;
}
}
update_cart();
});
});
const remove_button = document.getElementsByClassName("remove");
[...remove_button].forEach((button) => {
button.addEventListener("click", function () {
const index = this.getAttribute("index");
cart.splice(index, 1);
update_cart();
});
});
}
};