0

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
5
  • NULL is the same as null - you don't need to compare against it twice. Commented Dec 26, 2010 at 15:59
  • @nickf: ok, why is giving me all the values even if I don`t type in any! Commented Dec 26, 2010 at 16:01
  • getElementsByName returns an array of objects. you need an outer loop to loop through those and an inner to loop through the items in each array. Commented Dec 26, 2010 at 16:01
  • @josh.trow: how can I accomplish this? Commented Dec 26, 2010 at 16:02
  • you can shorten the if() to if (overheads[i].value) Commented Dec 26, 2010 at 17:22

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

if Im using floats, shall I use parseFloat` instead of parseInt??
@sikas Yep. It would work the same (but you know, with floats). I only used parseInt because it's used in the OP.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.