I'm new to js and have been going crazy trying to get this to work. I need the script to pull the values in the class selected, then spit out the sum of them. It can't be that hard! This is what I have and it just won't run. I'm working in a intra environment, so I'm not too worried about cross-browser compatibility. Any help would be appreciated. Thank you.

Both you and Xelawho put it in the WRONG PLACE! It must go *AFTER* the loop.

not necessarily... it alerts as 1000 on the first loop and 2000 on the second. Depends if you want a running total or all in one hit at the end. Either way, when the loop ends you get an alert of 2000

And Xelawho put the variable sum in the wrong place! It needs to be *INSIDE* the function.

*if* you want it to be reset every time the function runs *and* you want it to remain local and not global. Otherwise it works fine.

but yeah - my answer was a little sloppy and Old Pedant's second code is obviously much better, just those "must" and "needs to be" are slightly misleading...

Old Pedant

03-24-2012, 01:45 AM

Welllllll....

I guess it depends on if you expect findTheOddOnes to be called more than once.

If not, doesn't matter where sum is initialized.

But if it might be called several times from several places, then the first time it is called the result will be 2000 (as the HTML was given). The second time it is called the sum will be 4000. Next time 6000. And so one. Seems pretty misleading to me.

So okay, maybe "must" for that is too strong. "Very likely" though, I would think.

Mishu

03-24-2012, 05:46 AM

MSIE 9 supports both, but SamHuff is right about any older version of MSIE.

Hello everyone.

You need to be aware that IE v9 needs a valid doctype at the top of the html before it will recognise document.getElementsByClassName(). Many newbies fall into the trap of not having a doctype.