PDA

View Full Version : Adding numbers together from a form


greenshoes
09-27-2002, 09:13 AM
Hello, Apologies first this is no doubt simple,I am a newbie.

I have cobbled together this script to add some user input numbers from a form and display the sum of the numbers in a text field in the form. When I use the + character the numbers are treated as a string but when I use -,* or / the calculation is performed. How can I get the script to add 2 numbers together simply:


<SCRIPT language=JavaScript>
function calc(a,b) {
a = document.frm1.a.value;
b = a+document.frm1.b.value; insert *, - or / on this line it works but with + it doesn't

document.frm1.total1.value = b;
}
</SCRIPT>

</head>

<body bgcolor="#FFFFFF"
<FORM name=frm>
<TABLE border=0>

<TR>
<TD> <INPUT name=a> + <INPUT size=5 name=b>?</TD>
<TD> = <INPUT name=total></TD>
<TD><INPUT onclick=calc() type=button value=Calculate></TD>
<TD> <INPUT type=reset value=Reset></TD></TR></TABLE></FORM>
</body>

glenngv
09-27-2002, 10:04 AM
it is because + sign is also a string operator which is used to concatenate 2 or more strings

so you have to cast it like this:

b = a+parseInt(document.frm1.b.value);

if you want decimal places you will use:

b = a+parseFloat(document.frm1.b.value);

take note that if the value can't be converted to a number, the method returns NaN (Not-a-Number)
so you have to check for a number using
isNaN(document.frm1.b.value)
which returns true if not a number, false otherwise

greenshoes
09-27-2002, 10:44 AM
Hi Glen, I have tried using both the operators you suggested but the calculation is still being treated as a string. Below is the code for the whole page, would different web browsers interpret this code in different ways I am running IE5.5. </html>:mad:

<html>
<head>
<SCRIPT language=JavaScript>

function calc(a,b) {
a = document.frm.a.value;
b = a+parseFloat(document.frm.b.value);
document.frm.total.value = b;
}


//-->
</SCRIPT>


</head>

<body bgcolor="#FFFFFF" text="#000000">
<FORM name=frm>
<TABLE border=0>

<TR>
<TD> <INPUT name=a> + <INPUT name=b>
</TD>
<TD> =<INPUT name=total></TD>
<TD><INPUT onclick=calc() type=button value=Calculate></TD>


<TD> <INPUT type=reset value=Reset></TD></TR></TABLE></FORM>
</body>

glenngv
09-27-2002, 10:56 AM
function calc() {
b = parseFloat(document.frm.a.value)+parseFloat(document.frm.b.value);
document.frm.total.value = b;
}

greenshoes
09-27-2002, 11:06 AM
Hoorah, thanks Very much Glen, that works properly. I now promise to do my Javascript tutorials rather than having to take up peoples time on simple queries.

Cheers!!

:D