Javascript: avoid windows to reload

I have this form that is never submitted: it just runs the function calcularplazas()when the button is clicked without submitting:

<form name="what" id="what" action="">   
  <input id="mat" type="text"/>
  <button id="btnEnviar" class="btn" onclick="calcularplazas();">SEND</button>                         
  <input id="btnLimpiar" class="btn" type="reset" value="CLEAR" />
  <p id="resultado"></p>
 </form>  

When you click on the button, the function works correctly, but the result cannot be shown, since the window reloads. I do not understand this behavior, since nothing happens in the function that forces it to reload, and is not a form submission.

As a result of this, the text of the result is exported to <p id="resultado"></p>, but in miliseconds it disappears when the window reloads.

Why is this behavior?

function calcularplazas(){    

        var mensaje = "MENSAJE FINAL";
        document.getElementById("resultado").innerHTML = mensaje;
}
+4
source share
4 answers

You can prevent the event submitfrom being sent.

myForm.addEventListener('submit', function(e) {
  e.preventDefault();
  calcularplazas();

  // do anything else you want
})

And HTML

<form id="myForm">   
  <input id="input1" type="text"/>
  <button type="submit" id="myButton">SEND</button>                         
</form>

Return,

+2

" ", <button> a type, . , "" :

<button type="button" id="btnEnviar" class="btn" onclick="calcularplazas();">SEND</button> 

.

+6

, = "button"? type = "submit" ( , ).

0

2 .

  • return false javascript.
  • onclick function write return calcularplazas.

check the code below for reference.

function calcularplazas () {    

        var mensaje = "MENSAJE FINAL";
        document.getElementById ("resultado"). innerHTML = mensaje;
        return false;
}
  <button id="btnEnviar" class="btn" onclick="return calcularplazas();">SEND</button>                         
0
source

Source: https://habr.com/ru/post/1620731/


All Articles