...

View Full Version : simple calculator, + doesn't work



pgb
06-30-2006, 11:36 AM
With this simple calculator + doesn't work, it puts numbers together instead of adding.
* / - all work fine



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Calculate</title>
</head>
<body>
<script type="text/javascript" language="javascript">
<!--

function checkform() {

var num1=document.addnumbers.num1.value; //get the first number from the form send it to a variable called num1

var num2=document.addnumbers.num2.value; //get the second number from the form send it to a variable called num2

function calculate (a,b) //create a function called calculate that will do a + b = x
{x = a + b; //this works fine with *, /, and -, but not with +, which it treats like a string!
return x;}

var total=calculate(num1,num2) //create a variable called total that will use the calculate function on num1 and num2

alert ("The total is " + total) //alert box will display total when form submitted

}

-->
</script>


<form onsubmit="return checkform()" name="addnumbers" action="" method="post">


Number 1<input type="text" name="num1"><br />
Number 2 <input type="text" name="num2"><br />



<input type="submit" class="button" value="Get the total!" />



</form>


</body>
</html>

_Aerospace_Eng_
06-30-2006, 12:01 PM
Thats because the values are returned as strings. You can use Number(), parseInt() or parseFloat(). I prefer Number() since it can handle ints and floats

var num1=Number(document.addnumbers.num1.value); //get the first number from the form send it to a variable called num1

var num2=Number(document.addnumbers.num2.value); //get the second number from the form send it to a variable called num2

CSTruter
06-30-2006, 12:02 PM
Its simply a conversion to Integer that needs to happen here.

function calculate (a,b)
{
x = (a-0) + (b-0); return x;
}

pgb
06-30-2006, 12:09 PM
Thanks! :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum