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)">

3 Answers 3

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().

Sign up to request clarification or add additional context in comments.

Comments

1

This works:

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

Comments

0

This is more safe (see this):

Calc.ans.value = parseInt(Calc.n1.value, 10) + parseInt(Calc.n2.value, 10)

2 Comments

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?
Yes, I agree with you! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.