Add multiple variables in a JS loop


I have multiple inputs (class .fat-calc1 to .fat-calc24) and a result place (class fat-result). I want to make a loop that adds inputs (.fat-calc1 + .fat-calc2 + ... + .fat-calc24) and displays that in the result div.

<div class='fat-calc-col'>
  <input type='number' name='fat-calc1"' class='fat-calc fat-calc1'>
  <input type='number' name='fat-calc2"' class='fat-calc fat-calc2'>
  <input type='number' name='fat-calc2"' class='fat-calc fat-calc2'>
  <div class='calc-result fat-result'></div>
$(".fat-calc-col").children().on('input', function(e){

    var fat = [];
    let result = "";
    for (let x = 1; x <= 24; x++) {
        fat[x] = parseFloat($(".fat-calc" + x).val());
        fat[x] = fat[x] ? fat[x] : 0;
        result += fat[x];


When you type 1 into fat-calc1 and 3 into fat-calc2 the result it not 4, but 130000000000000000000000. I was trying to add parseFloat to basically everything I could, but it didn’t work. Why does that happen? How to fix it?


You add it all to string. Change it
let result = "";
to it
let result = 0;

Answered By – Lukas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published