View Full Version : simple question (really!) from newbie

10-17-2005, 08:50 PM
I have a simple web form with several fields, and want to dynamically calculate the total when the visitor moves from one field to another. I find that when I use the addition operator (+), the fields are concatenated instead of added. (That is to say, values 1 and 2 in the form are showed as 12 instead of 3.) My test with other operators (ie, *) shows that the variables can indeed be treated as numeric values. Is there a different operator I should be using to force values to be added?

For reference, the script is below and the code of my form is below that.



function addem2(frm2) { frm2.grandtotal.value = frm2.v01.value + fm2.v02.value }


<form name="frm2" method="get">
<input type="TEXT" name="v01" value="" size="6" maxlength="5" onChange="addem2(this.form)"><br>
<input name="v02" type="TEXT" id="v02" onChange="addem2(this.form)" value="" size="6" maxlength="5"><br>
<input type="TEXT" name="grandtotal" value="" size="6">

10-17-2005, 09:12 PM
This is the most common newby problem, so you are not alone

Text box values are strings

'4' + '4' = '44'

therefor the string must be converted to a number


Number('4') = 4;

parseInt('4') =4;

parseInt('4.4')= 4;


Number('4.4')= 4.4;

Number('4.4')+'4.4' = '4.44.4';

mutiplying or dividing a valid string number will autotype to a number

'4.4'*2 = 8.8;

to check for a valid number

isNaN('4.4) is false

isNaN('4.4X') is true

to replace none digits

x.value=x.value.replace(/\D/g,''); // result is still a string but is only digit charactors

10-17-2005, 10:31 PM
awesome. thank you very much !!

10-18-2005, 07:14 AM
function addem2(frm2) { frm2.grandtotal.value = (frm2.v01.value*1) + (frm2.v02.value*1) }

If you times each number by 1 you can add them that way too, the same way he said above. :thumbsup:

10-18-2005, 09:02 AM
HE said

mutiplying or dividing a valid string number will autotype to a number