-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcart.js
More file actions
47 lines (37 loc) · 1.41 KB
/
cart.js
File metadata and controls
47 lines (37 loc) · 1.41 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
const cartContainer = document.getElementById("cart-container");
const grandTotal = document.getElementById("grand-total");
let cartItems = JSON.parse(localStorage.getItem("cart")) || [];
function displayCart() {
cartContainer.innerHTML = "";
let total = 0;
cartItems.forEach((item, index) => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
const itemDiv = document.createElement("div");
itemDiv.className = "cart-item";
itemDiv.innerHTML = `
<img src="${item.image}" alt="${item.name}">
<p>${item.name}</p>
<p>₹${item.price}</p>
<input type="number" min="1" value="${item.quantity}" data-index="${index}">
<p>₹${itemTotal}</p>
<button onclick="removeItem(${index})">Remove</button>
`;
cartContainer.appendChild(itemDiv);
});
grandTotal.innerText = total;
}
function removeItem(index) {
cartItems.splice(index, 1);
localStorage.setItem("cart", JSON.stringify(cartItems));
displayCart();
}
cartContainer.addEventListener("input", function(e) {
if (e.target.tagName === "INPUT") {
const index = e.target.dataset.index;
cartItems[index].quantity = parseInt(e.target.value);
localStorage.setItem("cart", JSON.stringify(cartItems));
displayCart();
}
});
displayCart();