forked from khushi-joshi-05/Food-ordering-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcart.js
69 lines (57 loc) · 2.05 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
63
64
65
66
67
68
69
function addItemToCart() {
var itemName = localStorage.getItem('itemName');
var itemPrice = localStorage.getItem('itemPrice');
addToCart(itemName, itemPrice);
}
const addToCart = function(name, price){
let cartItems = localStorage.getItem('cartItems');
cartItems = cartItems ? JSON.parse(cartItems) : [];
if(name==null && price==null) return;
const existingItem = cartItems.find(item => item.name === name);
if (!existingItem) {
cartItems.push({ name, price });
localStorage.setItem('cartItems', JSON.stringify(cartItems));
console.log(cartItems);
}
updateCartDisplay();
calculateBill();
}
const updateCartDisplay = function() {
const cartBody = document.querySelector(".items");
cartBody.innerHTML = '';
let cartItems = localStorage.getItem('cartItems');
cartItems = cartItems ? JSON.parse(cartItems) : [];
cartItems.forEach(item => {
const cartRow = document.createElement("tr");
const cartItemName = document.createElement("td");
const cartItemPrice = document.createElement("td");
cartItemName.innerText = item.name;
cartItemPrice.innerText = item.price;
cartItemPrice.classList.add("price");
cartRow.appendChild(cartItemName);
cartRow.appendChild(cartItemPrice);
cartBody.appendChild(cartRow);
});
}
// calculate total bill amount
const calculateBill = ()=>{
let total = 0;
itemPrices = document.querySelectorAll(".price");
for (p of itemPrices){
if (p!=null){
console.log(p.innerText);
total += parseFloat(p.innerText.replace('$',''));
}
}
console.log(total);
if(total!=0 && !isNaN(total)){
document.getElementById("bill").innerText = "$" + total.toFixed(2)
}
}
document.addEventListener('DOMContentLoaded', function () {
addItemToCart();
});
let orderBtn = document.querySelector(".butt");
orderBtn.addEventListener("click", ()=>{
alert("Order placed!");
})