Click to See Complete Forum and Search --> : concatenating...?


xataku_nakusute
07-25-2003, 02:45 PM
im trying to make a calculator-like script just to test out....and i have it set so that it will calculate the value of inputs a and b......however, this produces odd(yet funny as heck) answers such as 1+1=11 and 0+1=01(that one works..)

so basically, my "calculator" is just concatenating the inputted data.......and becuz of this odd bug, ive named my code: "Baby's First Calculator" hehe

my code is included, pleaz help me to get it to actually add!!!

<html>
<body>
<script type="text/javascript">
function add(a1,a2)
{
a1 = document.calculator.add1.value
a2 = document.calculator.add2.value
equals = a1+a2
document.write(equals);
}
</script>
<center>
<h1>"Baby's First Calculator"</h1>
<p>
<form name="calculator">
<input name="add1" type="text" maxlength="10000000" size="1">&nbsp;+&nbsp;
<input name="add2" type="text" maxlength="10000000" size="1">
<input value="Add" type="button" onclick="add()">
<input value="Reset" type="reset">
</form>
</center>
</body>
</html>

David Harrison
07-25-2003, 02:52 PM
It automatically assumes that the values entered are text. So rather than having:
a1=1;

It's like having:
a1="1"

What you could do is this:
a1 = document.calculator.add1.value*1;
a2 = document.calculator.add2.value*1;

And that should return the values that you want, but if any text or symbols are entered you'll just get the answer NaN, Not a Number.

xataku_nakusute
07-25-2003, 03:16 PM
thanx!.....

AdamBrill
07-25-2003, 03:25 PM
Actually, since the problem is that the values are strings, you should just convert it to a number. The basic command for that would be parseInt(). Your script would look like this:<html>
<body>
<script type="text/javascript">
function add(a1,a2)
{
a1 = parseInt(document.calculator.add1.value);
a2 = parseInt(document.calculator.add2.value);
equals = a1+a2;
document.write(equals);
}
</script>
<center>
<h1>"Baby's First Calculator"</h1>
<p>
<form name="calculator">
<input name="add1" type="text" maxlength="10000000" size="1"> +
<input name="add2" type="text" maxlength="10000000" size="1">
<input value="Add" type="button" onclick="add()">
<input value="Reset" type="reset">
</form>
</center>
</body>
</html>BTW, if the numbers can have decimals, then you should use parseFloat rather than parseInt.... ;)

xataku_nakusute
07-25-2003, 03:29 PM
thank you as well!