Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve() {
- const cartTextarea = document.querySelector('textarea');
- const checkoutButton = document.querySelector('.checkout');
- const addButtons = document.querySelectorAll('.add-product');
- const addedProducts = {};
- for (let index = 0; index < addButtons.length; index++) {
- addButtons[index].addEventListener('click', function() {
- const product = document.querySelectorAll('.product')[index];
- const productName = product.querySelector('.product-title').textContent;
- const productPrice = Number(product.querySelector('.product-line-price').textContent);
- if (addedProducts[productName]) {
- addedProducts[productName].quantity++;
- } else {
- addedProducts[productName] = {
- price: productPrice,
- quantity: 1,
- };
- }
- cartTextarea.value += `Added ${productName} for ${productPrice.toFixed(2)} to the cart.\n`;
- });
- }
- checkoutButton.addEventListener('click', function() {
- let totalPrice = 0;
- const uniqueProducts = [];
- for (const productName in addedProducts) {
- if (addedProducts.hasOwnProperty(productName)) {
- const product = addedProducts[productName];
- totalPrice += product.price * product.quantity;
- uniqueProducts.push(productName);
- }
- }
- cartTextarea.value += `You bought ${uniqueProducts.join(', ')} for ${totalPrice.toFixed(2)}.`;
- for (let index = 0; index < addButtons.length; index++) {
- addButtons[index].disabled = true;
- }
- checkoutButton.disabled = true;
- });
- }
- OR
- function solve() {
- const products = document.querySelectorAll('.product');
- const cartTextarea = document.querySelector('textarea');
- const checkoutButton = document.querySelector('.checkout');
- const addButtons = Array.from(document.querySelectorAll('.add-product'));
- const addedProducts = [];
- addButtons.forEach((button, index) => {
- button.addEventListener('click', () => {
- const product = products[index];
- const productName = product.querySelector('.product-title').textContent;
- const productPrice = Number(product.querySelector('.product-line-price').textContent);
- addedProducts.push({ name: productName, price: productPrice.toFixed(2) });
- cartTextarea.value += `Added ${productName} for ${productPrice.toFixed(2)} to the cart.\n`;
- });
- });
- checkoutButton.addEventListener('click', () => {
- const totalPrice = addedProducts.reduce((total, product) => total + parseFloat(product.price), 0);
- const uniqueProducts = [...new Set(addedProducts.map(product => product.name))];
- cartTextarea.value += `You bought ${uniqueProducts.join(', ')} for ${totalPrice.toFixed(2)}.`;
- addButtons.forEach(button => button.disabled = true);
- checkoutButton.disabled = true;
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement