1

So, I'm relatively new to JavaScript and I was wondering how I would add the values from two inputs and echo out the result. Here's what I have so far:

function math (form) {
    var input1 = form.input1.value;
    var input2 = form.input2.value;
    var input3 = input1 + input2;
    document.write (input3);
}
<form action="" method="GET">
   <input type="text" name="input1">
   <input type="text" name="input2">
   <input type="button" name="button" onClick="math(this.form)">
</form> 

I expected that when I entered a number into each input it would spit out the sum of the two numbers. Instead it just prints both numbers individually.

How can I get it to print the sum of the two numbers?

5 Answers 5

17

.value gives the characters in the textbox, i.e. a string. You somehow need to tell JavaScript that it's a number. Otherwise you're concatenating the strings (str + str is concatenating; num + num is adding arithmetically).

String to number conversion is most easily done with + like this:

+input1

So in your case:

document.write(+input1 + +input2);

However, document.write is not the way to display things. You probably want alert, or put it in another textbox or something like that. document.write will clear the screen.

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

1 Comment

thanks for the tip. I was just using document.write temporarily until I got some other stuff sorted out.
12

They are strings when you read them in, they must be parsed first,

var input3 = parseInt(input1, 10) + parseInt(input2, 10);

[Edit] Just to elaborate, the difference between parseInt and the Unary Plus is in the error handling,

var a = parseInt('123o45', 10); //123
var b = +'123o45' // NaN

1 Comment

+1 for pointing out the difference between parseInt and Unary Plus.
3

parseInt is your firend here..

function math (form) {
  var input1 = form.input1.value;
  var input2 = form.input2.value;
  var input3 = parseInt(input1, 10) + parseInt(input2, 10);
  document.write (input3);
}

1 Comment

ParseInt without specifying the radix is generally a bad idea. Should be parseInt(input1, 10) to make sure it parses all strings as decimal.
1

You would have to parse them to integers first using parseInt.

Comments

0

Mine worked well with parsing them to Float as I am having decimal digits. Instead of parseInt(), I used parseFloat().

I hope it'll help somebody in future.

Comments

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.