Calculate sum from user input form fields

Hello, I am using a script to calculate the total of a column of input fields where the user enters amounts. I customized this script for my form and it works, except that if one of the fields is left blank it display “NaN” in my total instead of counting the blank field as zero and giving me a real total.

[COLOR="Blue"][B]This is in the <head>:[/B][/COLOR]
<script type="text/javascript">
function calculate() {
var total = 0;

for (var i = 1; i < arguments.length; i++) {
total += parseInt(arguments[i].value, 10);

arguments[0].value = total;

[B][COLOR="blue"]This is my input fields... ( I have 13 fields in total):[/COLOR][/B]
<input type="text" name="Tuition" size="15" tabindex="32">

[B][COLOR="blue"]This is the calculate button and the total field:[/COLOR][/B]
<input type="button" value="Calculate Column" onclick="calculate(, this.form.Tuition, this.form.Books, this.form.Rent, this.form.Utilities, this.form.Heating, this.form.Food, this.form.Clothing, this.form.Transportation, this.form.Entertainment, this.form.Insurance, this.form.Laundry, this.form.creditCard, this.form.BankLoans);">

<input type="text" name="total" size="15" tabindex="0">

How can I fix this the best possible way?

  1. making the script count the field as zero if blank instead of displaying “NaN”
  2. automaticly placing a zero in the field with the onBlur event.

I’m in the process of learning more JavaScript and I’m not sure how to add one of the above option without interfering with the main script.

Thanks for your advice!

Julia :cool:

n = parseInt(arguments[i].value, 10);
if (isNaN(n)) {
  n = 0;
total += n;

or this does the same:

total += parseInt(arguments[i].value, 10) || 0;

Wow, short and efficient, that’s the way I like code. Thanks a lot Mike!

:slight_smile: :tup: