I am trying to figure out how to sum and display input numbers as live calculation.
It kind of works but the calculations are wrong. With each iteration it adds bigger number, like in arithmetic sequence. How do I solve this?
"use strict";
let tot = 0;
let myInputField = document.querySelectorAll(".score");
myInputField.forEach((el) => {
el.addEventListener("input", () => {
for (let i = 0; i < myInputField.length; i++) {
if (parseInt(myInputField[i].value))
tot += parseInt(myInputField[i].value);
}
document.getElementById("total").value = tot;
});
});
<p><input type="text" class="score" id="myInputField12"></input>
</p>
<p><input type="text" class="score" id="myInputField13"></input>
</p>
<p><input type="text" class="result" id="total"></input>
</p>
</div>
Here’s codepen: https://codepen.io/Bartosz-Spychaa-the-bold/pen/GRPNwYa?editors=1111
2
Answers
Delegate and map/reduce
Also the HTML was invalid
Calculation issue in Event Listener in JS
The issue is that the
tot
variable is declared outside of theaddEventListener
callback. This means that each time you input a value, it adds the current total of all inputs to the existing value of thetot
variable.How To: Fix it: Reset the
tot
variable to 0 at the beginning of every input event.Fixed JavaScript:
The fixed
JavaScript
should solve your issue. If you still have any problem or question feel free to ask.