Advertisement
ilianrusev

06.Furniture

Jan 15th, 2022
1,019
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.   input = document.getElementById('exercise').children[1];
  3.  
  4.   document.getElementById('container').addEventListener('click', onClick);
  5.  
  6.   function onClick(ev) {
  7.     if (ev.target == document.querySelectorAll('button')[0]) {
  8.       let arr = JSON.parse(input.value)
  9.  
  10.       for (let i = 0; i < arr.length; i++) {
  11.         let newRow = document.createElement('tr')
  12.         document.getElementsByTagName('tbody')[0].appendChild(newRow);
  13.         let all = document.querySelectorAll('tbody tr');
  14.         let currentRow = all[all.length - 1];
  15.         let newTd;
  16.  
  17.         for (let j = 0; j < Object.keys(arr[i]).length; j++) {
  18.  
  19.           newTd = document.createElement('td');
  20.           if (j == 0) {
  21.             let newImg = document.createElement('img');
  22.             newImg.src = arr[i]["img"];
  23.             newTd.appendChild(newImg)
  24.             currentRow.appendChild(newTd);
  25.           } else {
  26.             let newPar = document.createElement('p');
  27.             newPar.textContent = Object.values(arr[i])[j]
  28.             newTd.appendChild(newPar);
  29.             currentRow.appendChild(newTd);
  30.           }
  31.         }
  32.         let newInput = document.createElement('input');
  33.         newInput.type = "checkbox";
  34.         newTd = document.createElement('td');
  35.         newTd.appendChild(newInput);
  36.         currentRow.appendChild(newTd);
  37.       }
  38.     } else if (ev.target == document.querySelectorAll('button')[1]) {
  39.       let furniture = []
  40.       let totalPrice = 0;
  41.       let resultFactor = 0;
  42.  
  43.       let checkboxes = Array.from(document.querySelectorAll('tbody tr'));
  44.  
  45.       for (let i = 0; i < checkboxes.length; i++) {
  46.         let currentCheck = checkboxes[i].getElementsByTagName('input')[0];
  47.         if (currentCheck.checked == true) {
  48.           let name = currentCheck.parentNode.parentNode.querySelectorAll('p')[0].textContent;
  49.           let price = currentCheck.parentNode.parentNode.querySelectorAll('p')[1].textContent;
  50.           let factor = currentCheck.parentNode.parentNode.querySelectorAll('p')[2].textContent;
  51.           furniture.push(name);
  52.           totalPrice += Number(price);
  53.           resultFactor += Number(factor);
  54.  
  55.         }
  56.       }
  57.       document.getElementsByTagName('textarea')[1].value = `Bought furniture: ${furniture.join(', ')}\nTotal price: ${totalPrice.toFixed(2)}\nAverage decoration factor: ${resultFactor / furniture.length}`
  58.  
  59.     }
  60.   }
  61. }
  62.  
Advertisement
RAW Paste Data Copied
Advertisement