Replace anchor by button in form with calculation by javascript

7

I have the following code:

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="">
  <a href="#" onclick="calc();">Calcular</a>
</form>

I would like to replace the <a> tag with a <button> , but when doing so the page updates soon after the calculation and the result is not visible. Here in post does not update after I click the button, but on my local page yes.

    
asked by anonymous 25.12.2016 / 23:24

1 answer

7

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>
    
25.12.2016 / 23:34