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()" />
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.