Calculate in javascript without refreshing the page

2

I'm trying to create a script in javascript to get a value entered by the user, and multiply by the specified value, but every time I click the button, it does the calculations, but it refreshes the page then zeroes.

Here is the code I used:

document.getElementById("btn").onclick = function() {
  var valorProduto = "";
  valorProduto = document.getElementById("vp").value * 2;
  document.getElementById("valorST").innerHTML = valorProduto;
}
<p>Valor do produto:
  <input type="text" id="vp">
</p>
<p id="valorST">valor</p>
<button id="btn">Calcular</button>
    
asked by anonymous 10.01.2017 / 17:35

1 answer

1

Puts a return false; in the last line of the script, so it runs the script. Maybe it has a <form> there and it understands the button as submit .

document.getElementById("btn").onclick = function() {
  var valorProduto = "";
  valorProduto = document.getElementById("vp").value * 2;
  document.getElementById("valorST").innerHTML = valorProduto;
  return false;
}
<p>Valor do produto:
  <input type="text" id="vp">
</p>
<p id="valorST">valor</p>
<button id="btn">Calcular</button>
    
10.01.2017 / 17:38