I believe that if I understand correctly, just put a button of type not Ubmit, not to send the form and reload the page without you see the result!
function calc(){
var form = document.getElementById("form");
var a = +form.a.value;
var b = +form.b.value;
var result = (a+b);
form.result.value = result;
}
<form id="form">
A: <input type="number" name="a">
B: <input type="number" name="b">
Result: <input type="text" name="result" disabled="">
<input type="button" onclick="calc();" value="Calcular">
</form>
Worth remembering that the operator +
used after equal sign, as in the case used:
var a = +form.a.value;
It is used to indicate the input of a positive number, since returning the value of an input, by default will come as String
. I mean, if I didn’t have the +
, and simply put (a+b)
would be understood as two strings, concatenate instead of adding them.Here is the example below:
function calc(){
var form = document.getElementById("form");
var a = form.a.value;
var b = form.b.value;
var result = (a+b);
form.result.value = result;
}
<form id="form">
A: <input type="number" name="a">
B: <input type="number" name="b">
Result: <input type="text" name="result" disabled="">
<input type="button" onclick="calc();" value="Calcular">
</form>
In short:
var um = "1" ;
var b = um ; // B = "1": uma string
var c = + um ; // C = 1: um número
var d = - um ; // d = -1: um número
And another way to get the same result would be to "convert" the value from the input, using Eval:
function calc(){
var form = document.getElementById("form");
var a = form.a.value;
var b = form.b.value;
var result = (eval(a)+eval(b));
form.result.value = result;
}
<form id="form">
A: <input type="number" name="a">
B: <input type="number" name="b">
Result: <input type="text" name="result" disabled="">
<input type="button" onclick="calc();" value="Calcular">
</form>
I don’t quite understand what you want...
– LocalHost
In place of the tag
<a>
would like to put a<button>
, but when doing this the page refreshes right after the calculation and the result is not visible.– Laércio Lopes
Try the way I answered there. if not comment...
– LocalHost