I think if I understood correctly, you just put a button of type do not submit, not 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>
It is worth remembering that the +
operator used after the equality sign, as in the case used:
var a = +form.a.value;
It is used to indicate the entry of a positive number, since returning the value of an input, by default will come as String
. That is, if it did not have +
, and simply put (a+b)
would be understood as two strings, it would concatenate instead of sum them. Follow 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>