I am trying to get the values of several fields & add them together & in my testing I am having problems. I have this code:
var count;
function calculate() {
// Fix jQuery conflicts
jQuery.noConflict();
count = 0;
jQuery('.calculate').each(function() {
var currentElement = jQuery(this);
var value = currentElement.val();
var count = count + value;
alert(count);
});
}
I enter in the value of “9” in my first field & when the first alert triggers I get “undefined9”; all the other values are currently set to “0”; when it triggers again I always get “undefined0”.
Why am I getting the “undefined” bit & why is it only returning the value of the current field & not adding them together?
You are dimensioning the
countvalue inside the loop, essentially setting it toundefinedfirst in each iteration.You want to remove the
varwithin the loop. This way, it doesn’t have scope to the anonymous function and JavaScript will look at the parent function for its declaration.It may also be a good idea to
parseInt(count, 10)the number first, because JavaScript overloads the+operator to mean arithmetic addition and string concatenation, and you wouldn’t wantcountto be"0something".Finally,
count += valueis easier to read 🙂