2

This is the code when I am adding in all textbox it works fine but after removing number it shows NaN:

function sumVal()
{
    var total = 0;
    var coll = document.getElementsByTagName("input")
    for ( var i = 0; i<coll.length; i++)
    {
        var ele = coll[i];
        total += parseInt(ele.value);
    }
    var Display = document.getElementById("Display");
    Display.innerHTML = total;
}

<input onkeyup="sumVal()" />
<input onkeyup="sumVal()" />
<input onkeyup="sumVal()" />
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mariraj Sankar
  • 69
  • 1
  • 1
  • 8

3 Answers3

4

Try checking that your value is NaN before adding it to the total:

total += (isNaN(parseInt(ele.value, 10)) ? 0 : parseInt(ele.value, 10));

Also, don't forget the radix for parseInt (or use parseFloat in the event you have decimal places):

radix

An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

var nums = [10, "sads", 44, 16];
var numsLen = nums.length;
var total = 0;

while(numsLen--){
    total += (isNaN(parseInt(nums[numsLen], 10)) ? 0 : parseInt(nums[numsLen], 10));
}

In this example, since "sads" is not a number (NaN) we add 0 to the total.

Chase
  • 29,019
  • 1
  • 49
  • 48
2

You should make sure that the element's value is a valid number first:

if (isNumber(ele.value))
    total += parseInt(ele.value, 10);
}

You'll need this function:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

The above function is the famous isNumber function from here.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
1

Just add 0 is if it's not a number:

var theInt = parseInt(ele.value, 10);
total += (isNaN(theInt)) ? 0 : theInt;
BenM
  • 52,573
  • 26
  • 113
  • 168