Replace anchor with button in form with calculation by javascript

Question:

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 put a <button> instead of the <a> tag, but when I do that the page refreshes right after the calculation and the result is not visible. Here in the post it doesn't update after I click the button, but on my local page it does.

Answer:

I believe that if I understand correctly, you just have to put a button like don't submit, so you don't send the form and reload the page without you seeing 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 is used after the 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 a String . That is, if you didn't have the + , and simply put (a+b) it would be understood as two strings, concatenating instead of adding 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>

Summing up:

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

E outra forma de se obter o mesmo resultado, seria “convertendo” o valor vindo do input, usando o 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>
Scroll to Top