0

My code just purely concatnates them and I want it to add them instead.

 <FORM NAME="Calc">
<TR>
<TD>
Number 1 <INPUT TYPE="text"   NAME="n1" Size="16">
Number 2 <INPUT TYPE="text"   NAME="n2" Size="16">
Answer<INPUT TYPE="text"   NAME="ans" Size="16">

<br>
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE="button" NAME="one"   VALUE="  +  " OnClick="Calc.ans.value = eval(Calc.n1.value + Calc.n2.value)">
Will Jamieson
  • 918
  • 1
  • 16
  • 32

3 Answers3

10

Like this:

Calc.ans.value = (+Calc.n1.value) + (+Calc.n2.value);

You don't need to use eval() here. In fact, you should (almost) never use eval().

JLRishe
  • 99,490
  • 19
  • 131
  • 169
1

This works:

Calc.ans.value = parseInt(Calc.n1.value) + parseInt(Calc.n2.value)
Aadrinmusic
  • 124
  • 9
0

This is more safe (see this):

Calc.ans.value = parseInt(Calc.n1.value, 10) + parseInt(Calc.n2.value, 10)
Community
  • 1
  • 1
leo
  • 1,243
  • 1
  • 18
  • 20
  • It's safer than using `parseInt()` without a radix, but the `+` operator doesn't have the issue mentioned in the page you linked to. Plus, are you sure that the numbers OP wants to use are limited to integers? – JLRishe Apr 11 '14 at 15:54
  • Yes, I agree with you! ;) – leo Apr 14 '14 at 09:54