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?
.valuegives 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 + stris concatenating;num + numis adding arithmetically).String to number conversion is most easily done with
+like this:So in your case:
However,
document.writeis not the way to display things. You probably wantalert, or put it in another textbox or something like that.document.writewill clear the screen.