`document.addEventListener('DOMContentLoaded', (event) => {
$(document).ready(function() {
// Function to update the cart subtotal and full cart
function updateCartTotals() {
let subtotal = 0;
$('.cart-total-price').each(function() {
subtotal += parseFloat($(this).text().replace('$', ''));
});
// Update the cart subtotal
$('.cart-subtotal').text('$' + subtotal.toFixed(2));
// Update the full cart
$('.full-cart').text('$' + subtotal.toFixed(2));
}
// Call the updateCartTotals function when the page loads
updateCartTotals();
// Call the updateCartTotals function when a cart item is added or removed
$(document).on('click', '.cart-remove', function() {
updateCartTotals();
});
$(document).on('change', '.cart-quantity input', function() {
updateCartTotals();
});
});
function removeCartItem(event) {
// Get the button element that was clicked
var buttonClicked = event.target;
// Get the table row (TR element) containing the button
var tableRow = buttonClicked.closest('tr');
// Get the product name from the table row
var productName = tableRow.getElementsByClassName('cart-pro')[0].innerText;
// Get the existing cart from localStorage
var cart = JSON.parse(localStorage.getItem('cart')) || [];
// Find the index of the product in the cart
var productIndex = cart.findIndex(function(item) {
return item.name === productName;
});
// If the product is found in the cart, remove it
if (productIndex > -1) {
let removedItem = cart.splice(productIndex, 1)[0];
// Save the updated cart back to localStorage
localStorage.setItem('cart', JSON.stringify(cart));
// Remove the table row
if (tableRow) {
tableRow.remove();
}
}
}
// Quantity Changes
function quantityChanged(event){
var input = event.target
if (isNaN(input.value) || input.value <= 0){
input.value = 1;
}
}
// register products from shop to sproduct
let pro1 = document.querySelector('.pro1');
if (pro1) {
pro1.addEventListener('click', function() {
let imgSrc = this.querySelector('.r-img').src;
let category = this.querySelector('.Category').textContent;
let productName = this.querySelector('.product').textContent;
let price = this.querySelector('.shop-price').textContent;
let description = this.querySelector('.main-desc').textContent;
localStorage.setItem('imgSrc', imgSrc);
localStorage.setItem('category', category);
localStorage.setItem('productName', productName);
localStorage.setItem('price', price);
localStorage.setItem('description', description);
window.location.href = 'sproduct.html';
});
}
// Then, in sproduct.html, you can retrieve these details from localStorage
window.onload = function() {
const mainImg = document.getElementById('MainImg');
const productName = document.querySelector('.sprod-pro-name');
const productPrice = document.querySelector('.sproduct-price');
const category = document.querySelector('.sprod-category');
const description = document.querySelector('.spro-main-desc');
if (mainImg && productName && productPrice) {
mainImg.src = localStorage.getItem('imgSrc');
category.textContent = localStorage.getItem('category');
productName.textContent = localStorage.getItem('productName');
productPrice.textContent = localStorage.getItem('price');
description.textContent = localStorage.getItem('description');
}
// register products from sproduct to cart
const addToCartButton = document.querySelector('#addCart');
const selectedSize = document.querySelector('.s-size');
const quantityInput = document.querySelector('.quantity');
if (addToCartButton) {
addToCartButton.addEventListener('click', function () {
const productImage = mainImg.src;
const name = productName.textContent.trim();
let price = parseFloat(productPrice.textContent.slice(1));
let pprice = parseFloat(productPrice.textContent.slice(1));
const size = selectedSize.value;
const quantity = parseInt(quantityInput.value);
if (size === 'M') {
pprice += 50;
}
else if (size === 'L') {
pprice += 100;
}
const product = {
image: productImage,
name,
price,
pprice,
size,
quantity,
};
let existingCart = [];
if (localStorage.getItem('cart')) {
existingCart = JSON.parse(localStorage.getItem('cart'));
}
existingCart.push(product);
localStorage.setItem('cart', JSON.stringify(existingCart));
// Show success message
document.getElementById('successPopup').style.display = 'block';
setTimeout(() => {
document.getElementById('successPopup').style.display = 'none';
}, 10000); // Hide success message after 10 seconds
window.location.href = 'cart.html';
});
}
};
// Functionality for cart.html
const cartData = JSON.parse(localStorage.getItem('cart')) || [];
function generateCartItem(item) {
let sizePrice = item.size === 'M' ? 50 : (item.size === 'L' ? 100 : 0);
return `
<tr>
<td><i class="bi bi-x-square-fill cart-remove"></i><a href="#"></a></td>
<td><img src="${item.image}" alt="" class="cart-img"></td>
<td class="cart-pro">${item.name}</td>
<td class="cart-price">$${item.price}</td>
<td class="cart-price1" style="display: none;">$${item.pprice}</td>
<td class="cart-quantity"><input type="number" value="${item.quantity}" min="0"></td>
<td class="cart-size">
<select class="c-size">
<option class="Small" ${item.size === 'S' ? 'selected' : ''}>S</option>
<option class="Medium" ${item.size === 'M' ? 'selected' : ''}>M</option>
<option class="Large" ${item.size === 'L' ? 'selected' : ''}>L</option>
</select>
</td>
<td class="cart-total-price">$${((item.price + sizePrice) * item.quantity).toFixed(2)}</td>
</tr>
`;
}
const cartItemsHTML = cartData.map(generateCartItem).join('');
if (document.querySelector('tbody')) {
document.querySelector('tbody').innerHTML = cartItemsHTML;
}
let sizes = document.querySelectorAll('.c-size');
let quantities = document.querySelectorAll('.cart-quantity input');
let prices = document.querySelectorAll('.cart-price1');
let totalPriceElements = document.querySelectorAll('.cart-total-price');
sizes.forEach((size, index) => {
let price = parseFloat(prices[index].innerText.replace('$', ''));
let totalPriceElement = totalPriceElements[index];
let lastSize = size.value;
let quantity = quantities[index];
let lastQuantity = parseInt(quantity.value);
size.addEventListener('change', function() {
let newSize = size.value;
if ((lastSize === 'S' && newSize === 'M') || (lastSize === 'M' && newSize === 'L')) {
price += 50;
} else if (lastSize === 'S' && newSize === 'L') {
price += 100;
} else if ((lastSize === 'L' && newSize === 'M') || (lastSize === 'M' && newSize === 'S')) {
price -= 50;
} else if (lastSize === 'L' && newSize === 'S') {
price -= 100;
}
lastSize = newSize;
totalPriceElement.innerText = '$' + (price * quantity.value).toFixed(2);
// Find the corresponding item in cartData and update its size and price
let item = cartData[index];
item.size = size.value;
item.price = price;
// Update the total price in the cart.html page
let subtotal = parseFloat(document.querySelector('.cart-subtotal').innerText.replace('$', ''));
document.querySelector('.cart-subtotal').innerText = '$' + (subtotal + (price * quantity.value) - (lastPrice * lastQuantity)).toFixed(2);
document.querySelector('.full-cart').innerText = '$' + (subtotal + (price * quantity.value) - (lastPrice * lastQuantity)).toFixed(2);
// Save the updated cartData to localStorage
localStorage.setItem('cart', JSON.stringify(cartData));
});
quantity.addEventListener('change', function() {
let newQuantity = parseInt(quantity.value);
if (newQuantity < lastQuantity) {
totalPriceElement.innerText = '$' + (price * newQuantity).toFixed(2);
} else {
totalPriceElement.innerText = '$' + (price * newQuantity).toFixed(2);
}
lastQuantity = newQuantity;
// Find the corresponding item in cartData and update its quantity
let item = cartData[index];
item.quantity = parseInt(quantity.value);
// Save the updated cartData to localStorage
localStorage.setItem('cart', JSON.stringify(cartData));
});
});
});`
cart.html
` <div id="subtotal">
<h3>Cart Totals</h3>
<table>
<tr>
<td>Cart Subtotal</td>
<td class="cart-subtotal"></td>
</tr>
<tr>
<td>Shipping</td>
<td>Free</td>
</tr>
<tr>
<td><strong>Total</strong></td>
<td class="full-cart"><strong></strong></td>
</tr>
</table>
<a href="checkout.html"><button class="normal">Proceed to checkout</button></a>
</div>
</div>`
1.When I select a size for an item in cart.html and refresh the page, the selected size gets reset. Please how can i correct this behavior.
2.When I change the size of an item in cart.html, the cart-total-price changes correctly, as it should. The same goes for the quantity change. However, the cart-subtotal and full-cart values are not being updated accordingly.
i tried using everything but i can’t find the bug pls help me