I calculate in javascript without refreshing the page

Asked

Viewed 791 times

2

I’m trying to create a script on javascript to take a value entered by the user, and multiply by the specified value, but whenever I click the button, it performs the calculations, but, it updates the page then zeroing.

Follow 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>

  • Puts a return false; after the last line of the script.

  • possibly your button may be inside a form, depending on how you have implemented this may give a refresh on the page if the action is empty if the action is completed, it will redirect, the return false; as told by @zooboomafoo can prevent this :)

  • Just one more thing, this has nothing to do with loop rs

  • I understood Marcelo, I really expressed myself wrong at first, rs

1 answer

1


Puts a return false; in the last line of the script, so it runs the script. Maybe you have a <form> there and he 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>

  • 1

    Yay! It worked! I removed the button from the form and added the code to the last line of js! Thanks :D

  • If it helped you just put the answer as correct. = D Which is below the polling arrows.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.