Skip to content

Commit

Permalink
Merge pull request #241 from Ishitamukherjee2004/main
Browse files Browse the repository at this point in the history
Bug in Cart Section is fixed successfully
  • Loading branch information
sunny0625 authored May 19, 2024
2 parents 4548b21 + 18119df commit 4b32ef6
Showing 1 changed file with 79 additions and 1 deletion.
80 changes: 79 additions & 1 deletion cart.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,80 @@

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
let total = 0;
const calculateBill = ()=>{
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", ()=>{
if(total==0){
alert("Please add something in the cart to place the order");
}
else{

alert("Order placed!");
}
})


// const applyFirstTimeDiscount = () => {
// let isFirstTimeUser = localStorage.getItem('isFirstTimeUser');
// if (!isFirstTimeUser) {
Expand All @@ -7,4 +84,5 @@
// document.getElementById('couponCode').innerText = `Use coupon code ${couponCode} for 30% off!`;
// alert(`Congratulations! Your coupon code is ${couponCode}. You've received a 30% discount on your first order.`);
// }
// }
// }

0 comments on commit 4b32ef6

Please sign in to comment.