skip to Main Content

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


  1. Delegate and map/reduce

    Also the HTML was invalid

    const scoreContainer = document.getElementById('scoreContainer');
    const fields = scoreContainer.querySelectorAll('.score');
    const totalField = document.getElementById('total');
    scoreContainer.addEventListener('input', () => {
      total.value = [...fields].map(field => {
        const val = +field.value; // convert to number
        return isNaN(val) ? 0 : val;
      }).reduce((a, b) => a + b);
    });
    <div id="scoreContainer">
      <p><input type="number" class="score" id="myInputField12" /></p>
      <p><input type="number" class="score" id="myInputField13" /></p>
      <p><input type="text" class="result" id="total" readonly /></p>
    </div>
    Login or Signup to reply.
  2. Calculation issue in Event Listener in JS

    The issue is that the tot variable is declared outside of the addEventListener callback. This means that each time you input a value, it adds the current total of all inputs to the existing value of the tot variable.

    How To: Fix it: Reset the tot variable to 0 at the beginning of every input event.

    Fixed JavaScript:

    "use strict";
    
    let myInputField = document.querySelectorAll(".score");
    
    myInputField.forEach((el) => {
      el.addEventListener("input", () => {
        let tot = 0; // Resets tot to 0 on each input event
        for (let i = 0; i < myInputField.length; i++) {
          if (parseInt(myInputField[i].value))
            tot += parseInt(myInputField[i].value);
        }
        document.getElementById("total").value = tot;
      });
    });

    The fixed JavaScript should solve your issue. If you still have any problem or question feel free to ask.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search