For more than two numbers, I would suggest another approach. I would create an empty array, then run a function that would get all inputs by class name, get their respective values and store those values into that empty array. Once we have all values stored, we can start working with them and make good use of the modern ES6 reduce method especially designed for array manipulation.
Codepen update: here
JavaScript:
// 🥦 when the DOM has loaded
document.addEventListener("DOMContentLoaded", () => {
// set globals
const inputs = document.getElementsByClassName("input"),
result = document.getElementById("result");
let value,
values = [],
sum;
// 🧄 for each input of the array
Array.from(inputs).forEach((input) => {
// get value of each input by explicit coercion
value = Number(input.value);
//inject each value into empty "values" array
values.push(value);
});
// 🥕 run a reduce function on the array
sum = values.reduce((a, b) => {
// return the sum of the accumulator (a) + its current value (b)
// in other words: 0(a) + 1(b) = 1 | 1(a) + 2(b) = 3 | 3(a) + 3(b) = 6
return a + b;
}, 0); // default accumulator's value starts with 0
// 🥗 inject result into the DOM + plural management
result.textContent = `${sum} minute${sum > 1 ? "s" : ""}`;
}); // end DOM loaded
HTML
<span>🥦 + </span><input class="input" type="hidden" value="1">
<span>🧄 + </span><input class="input" type="hidden" value="2">
<span>🥕 + </span><input class="input" type="hidden" value="3">
<!-- add as many input as you want... -->
<span>🥗 = </span><span id="result"><span>
Expected output:
+ + + = 6 minutes
Not sure about the quality of that salad thoug
I hope that helps.