Reputation: 6519
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?
Upvotes: 1
Views: 26759
Reputation: 492
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.
Upvotes: 0
Reputation: 911
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);
}
Upvotes: 3
Reputation: 13853
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
Upvotes: 12
Reputation: 33865
You would have to parse them to integers first using parseInt.
Upvotes: 1
Reputation: 154838
.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.
Upvotes: 17