|
|
@@ -0,0 +1,59 @@ |
|
|
|
const form = document.getElementById('input'); |
|
|
|
const inputContainer = document.getElementById('input-container'); |
|
|
|
const submitContainer = document.getElementById('submit-container'); |
|
|
|
let sumResult = document.getElementById('sum'); |
|
|
|
let productResult = document.getElementById('product'); |
|
|
|
let input = form.querySelectorAll('.input-field'); |
|
|
|
|
|
|
|
function addInputField(event) { |
|
|
|
let newField = document.createElement('div'); |
|
|
|
newField.classList.add('input-field'); |
|
|
|
newField.innerHTML = |
|
|
|
'<input type="number" /><input type="button" value="X" />'; |
|
|
|
inputContainer.appendChild(newField); |
|
|
|
} |
|
|
|
|
|
|
|
function removeInputField(event) { |
|
|
|
if (event.target.matches('input[type=button]')) { |
|
|
|
let element = event.target.closest('div'); |
|
|
|
if (element.parentNode.childElementCount > 2) { |
|
|
|
// https://www.w3schools.com/jsref/prop_element_childelementcount.asp |
|
|
|
element.parentNode.removeChild(element); |
|
|
|
// https://www.abeautifulsite.net/adding-and-removing-elements-on-the-fly-using-javascript |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
function calculateSum(array) { |
|
|
|
let result = 0; |
|
|
|
array.forEach(element => { |
|
|
|
result += parseInt(array[element].value); |
|
|
|
}); |
|
|
|
sumResult.innerHTML = 'sum: ' + result; |
|
|
|
} |
|
|
|
|
|
|
|
function calculateProduct(array) { |
|
|
|
let result = 0; |
|
|
|
array.forEach(element => { |
|
|
|
result *= parseInt(array[element].value); |
|
|
|
}); |
|
|
|
productResult.innerHTML = 'product: ' + result; |
|
|
|
} |
|
|
|
|
|
|
|
function updateResults(event) { |
|
|
|
if ( |
|
|
|
event.target.matches('input[type="number"]') || |
|
|
|
event.target.matches('input[name="calculate"]') |
|
|
|
) { |
|
|
|
let input = form.querySelectorAll('.input-field'); |
|
|
|
calculateSum(input); |
|
|
|
calculateProduct(input); |
|
|
|
} |
|
|
|
if (event.target.matches('input[name="add-input"]')) { |
|
|
|
addInputField(); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
form.addEventListener('input', updateResults); |
|
|
|
form.addEventListener('click', updateResults); |
|
|
|
submitContainer.addEventListener('click', removeInputField); |