
June 5th, 2001, 11:58 AM
|
|
Junior Member
|
|
Join Date: Jun 2001
Posts: 2
Time spent in forums: < 1 sec
Reputation Power: 0
|
|
Adding up text fields in Javascript
Hello all - I am new to this forum as I am new to the world of JS. I wanted to know if anyone can point me in the right direction on how to add JS to add up multiple fields in a HTML form I have created.
I use the eval() function to change entered text (in the fields in question) to numbers and the initial values of these fields is set to "" (value=""). My problem is how do I incorporate the empty fields (value="", i.e. the fields that have been left blank) to default to zero so that the addition function I created works?
Right now, after entering values in all the fields results in the right answer, but leaving one field empty results in NaN. I also would like not to have to use a default (value="0") of zero in those fields as it doesnt look as nice. Any help is greatly appreciated.
small Sample Code:
I have a series of Input statements 1-7 that look like this:
<input name="Amount1" size="10" value="" maxlength="10" onblur="doTotal(this.form)">
<input name="Amount2" size="10" value="" maxlength="10" onblur="doTotal(this.form)">
<input name="Amount3" size="10" value="" maxlength="10" onblur="doTotal(this.form)">
<input name="Amount4" size="10" value="" maxlength="10" onblur="doTotal(this.form)">
<input name="Amount5" size="10" value="" maxlength="10" onblur="doTotal(this.form)">
etc. etc. etc.
I would like to add these fields up into a "Total" field
<input readonly name="Total" size="10" value="" maxlength="10" >
My JS code looks like:
function doTotal(form) {
a=eval(form.Amount1.value);
b=eval(form.Amount2.value);
c=eval(form.Amount3.value);
d=eval(form.Amount4.value);
e=eval(form.Amount5.value);
f=eval(form.Amount6.value);
g=eval(form.Amount7.value);
form.Total.value = a + b + c + d + e + f + g;
}
Last edited by Zak Hanano : June 5th, 2001 at 12:15 PM.
|