You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.js 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const form = document.getElementById('input');
  2. const inputContainer = document.getElementById('input-container');
  3. const submitContainer = document.getElementById('submit-container');
  4. let sumResult = document.getElementById('sum');
  5. let productResult = document.getElementById('product');
  6. let input = form.querySelectorAll('.input-field');
  7. function addInputField(event) {
  8. let newField = document.createElement('div');
  9. newField.classList.add('input-field');
  10. newField.innerHTML =
  11. '<input type="number" /><input type="button" value="X" />';
  12. inputContainer.appendChild(newField);
  13. }
  14. function removeInputField(event) {
  15. if (event.target.matches('input[type=button]')) {
  16. let element = event.target.closest('div');
  17. if (element.parentNode.childElementCount > 2) {
  18. // https://www.w3schools.com/jsref/prop_element_childelementcount.asp
  19. element.parentNode.removeChild(element);
  20. // https://www.abeautifulsite.net/adding-and-removing-elements-on-the-fly-using-javascript
  21. }
  22. }
  23. }
  24. function calculateSum(array) {
  25. let result = 0;
  26. array.forEach(element => {
  27. result += parseInt(array[element].value);
  28. });
  29. sumResult.innerHTML = 'sum: ' + result;
  30. }
  31. function calculateProduct(array) {
  32. let result = 0;
  33. array.forEach(element => {
  34. result *= parseInt(array[element].value);
  35. });
  36. productResult.innerHTML = 'product: ' + result;
  37. }
  38. function updateResults(event) {
  39. if (
  40. event.target.matches('input[type="number"]') ||
  41. event.target.matches('input[name="calculate"]')
  42. ) {
  43. let input = form.querySelectorAll('.input-field');
  44. calculateSum(input);
  45. calculateProduct(input);
  46. }
  47. if (event.target.matches('input[name="add-input"]')) {
  48. addInputField();
  49. }
  50. }
  51. form.addEventListener('input', updateResults);
  52. form.addEventListener('click', updateResults);
  53. submitContainer.addEventListener('click', removeInputField);