kstoyanov

09. * Shopping Cart

Sep 29th, 2020 (edited)
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.     const productsInCart = [];
  3.     let totalPrice = 0;
  4.     const AddButtons = document.getElementsByClassName('add-product');
  5.     const textArea = document.getElementsByTagName('textarea')[0];
  6.     const checkoutButton = document.querySelector('.checkout');
  7.  
  8.    
  9.     Array.from(AddButtons).forEach( product => product.addEventListener('click', productClickHandler));
  10.     checkoutButton.addEventListener('click', checkoutClickHandler);
  11.    
  12.  
  13.     function productClickHandler(event) {
  14.        const addButtonDiv = event.target.parentElement;
  15.  
  16.        const name = addButtonDiv.previousElementSibling.children[0].textContent;
  17.        const money = addButtonDiv.nextElementSibling.textContent;
  18.  
  19.        textArea.value += `Added ${name} for ${money} to the cart.\n`;
  20.        if (!productsInCart.includes(name)) {
  21.            productsInCart.push(name);
  22.        }
  23.        totalPrice += Number(money);
  24.     }
  25.  
  26.     function checkoutClickHandler() {
  27.         textArea.value += `You bought ${productsInCart.join(', ')} for ${totalPrice.toFixed(2)}.`;
  28.         Array.from(AddButtons).forEach( button => button.disabled = true);
  29.         checkoutButton.disabled = true;
  30.     }
  31. }
Add Comment
Please, Sign In to add comment