I have incorporated the following script into my form to use in calculating a column in a balance sheet. The problem is, that if the user skips a field in the column, They get all kinds of errors. It doesn't always add, and sometimes it will look like this: 10.00 + 10.00 = 1,010.00.
This is the script that I used:
var f = this.getField("OA");
var a = f.getArray();
var sum = 0;
for (i =0; i < a.length; i++)
sum += a[i].value;
if (sum !=0)
event.value = sum;
else
event.value = "";
Is there a better script to use to calculate columns in a balance sheet?
Thanks for any assistance.
Connie
You need to explicitly convert the field values to numbers, which you can do with the unary + operator. Change this line:
sum += a[i].value;
to this:
sum += +a[i].value;
The '+' operator serves as both the addition operator for numbers and concatenation operator for strings. A null value is treated as a string value and not a numeric value, but a null string can be forced to a numeric value by forcing an operation that requires a numeric value or using the 'Number()' constrictor. Multiplication or division by 1 will force a number to zero. The use of the '+' operator is equivalent to multiplying by 1 like using the '-' in front of a variable is the same as multiplying by -1.
You should see the strange behavior when there is a null or empty field between 2 numeric values in the field.