I`m trying to sum the values of the elements in an array using javascript, this is my script.
function sumAll()
{
var totalOverheads = 0;
var overheads = new Array();
overheads = document.getElementsByName('overhead');
for(i=0;i<overheads.length;i++)
if(!isNaN(overheads[i].value) || overheads[i].value != null || overheads[i].value != "" || overheads[i].value != '' || overheads[i].value != NULL)
alert(overheads[i].value);
//totalOverheads = parseInt(totalOverheads) + parseInt(overheads[i].value);
alert(totalOverheads);
}
for now, in the if condition inside the for loop, I`m displaying the value of the item in an alert, yet it`s not working correctly, it just displays all the items even if the item is not a number, how can I perform an operation if the input is only a number?
asked Dec 26, 2010 at 15:55
sikas
5,54528 gold badges79 silver badges123 bronze badges
1 Answer 1
getElementsByName returns a NodeList. Not sure if that was the problem, but anyway:
var totalOverheads = 0;
var overheads = document.getElementsByName('overhead');
var n;
var i; // <<--- don't forget to initialise i
for (i = 0; i < overheads.length; ++i) {
n = parseInt(overheads.item(i).value, 10);
if (!isNaN(n)) {
totalOverheads += n;
}
}
alert(totalOverheads);
Also, please use brackets!
answered Dec 26, 2010 at 16:03
nickf
548k199 gold badges660 silver badges727 bronze badges
lang-js
NULLis the same asnull- you don't need to compare against it twice.if (overheads[i].value)