|
| 1 | +const addToCartButtons = document.querySelectorAll('.add-to-cart'); |
| 2 | +const cartItemsList = document.getElementById('cart-items'); |
| 3 | +const totalPriceElement = document.getElementById('total-price'); |
| 4 | +const placeOrderButton = document.getElementById('place-order'); |
| 5 | + |
| 6 | +let cart = []; |
| 7 | +let totalPrice = 0; |
| 8 | + |
| 9 | +const addToCart = (event) => { |
| 10 | + const itemName = event.target.dataset.name; |
| 11 | + const itemPrice = parseFloat(event.target.dataset.price); |
| 12 | + |
| 13 | + // Add item to cart |
| 14 | + cart.push({ name: itemName, price: itemPrice }); |
| 15 | + |
| 16 | + // Update total price |
| 17 | + totalPrice += itemPrice; |
| 18 | + |
| 19 | + // Add item to the cart UI |
| 20 | + const cartItem = document.createElement('li'); |
| 21 | + cartItem.textContent = `${itemName} - $${itemPrice.toFixed(2)}`; |
| 22 | + cartItemsList.appendChild(cartItem); |
| 23 | + |
| 24 | + // Update the total price displayed |
| 25 | + totalPriceElement.textContent = totalPrice.toFixed(2); |
| 26 | + |
| 27 | + // Enable the "Place Order" button |
| 28 | + placeOrderButton.disabled = false; |
| 29 | +}; |
| 30 | + |
| 31 | +addToCartButtons.forEach((button) => { |
| 32 | + button.addEventListener('click', addToCart); |
| 33 | +}); |
| 34 | + |
| 35 | +const placeOrder = () => { |
| 36 | + if (cart.length === 0) return; |
| 37 | + |
| 38 | + alert('Order placed successfully!'); |
| 39 | + cart = []; |
| 40 | + totalPrice = 0; |
| 41 | + |
| 42 | + // Clear cart UI |
| 43 | + cartItemsList.innerHTML = ''; |
| 44 | + totalPriceElement.textContent = '0.00'; |
| 45 | + |
| 46 | + // Disable the "Place Order" button again |
| 47 | + placeOrderButton.disabled = true; |
| 48 | +}; |
| 49 | + |
| 50 | +placeOrderButton.addEventListener('click', placeOrder); |
0 commit comments