dunyto

7. Shopping Cart

Jun 1st, 2022
1,033
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.     let textField = document.getElementsByTagName('textarea')[0];
  3.     let sum = 0;
  4.     let productsBought = [];
  5.     Array.from(document.querySelectorAll('.add-product')).forEach(i => { i.addEventListener('click', addItem); });
  6.     document.querySelector('.checkout').addEventListener('click', checkOut);
  7.  
  8.     function addItem(ev) {
  9.         let productName = ev.target.parentNode.previousElementSibling.firstElementChild.textContent;
  10.         if (!productsBought.includes(productName)) {
  11.             productsBought.push(productName);
  12.         }
  13.         let productPrice = Number(ev.target.parentNode.nextElementSibling.textContent);
  14.         sum += productPrice;
  15.         console.log(`Added ${productName} for ${productPrice} to the cart.\n`);
  16.         textField.value += `Added ${productName} for ${productPrice.toFixed(2)} to the cart.\n`;
  17.     }
  18.  
  19.     function checkOut(ev) {
  20.         textField.value += `You bought ${productsBought.join(", ")} for ${sum.toFixed(2)}.`;
  21.     }
  22.  
  23.     textField.value = "";
  24. }
Advertisement
Add Comment
Please, Sign In to add comment