Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: avoiding window to reload

Tags:

javascript

I have this form, that is never submitted: it just triggers a calcularplazas() function when pressing a non-submit button:

<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 clicking on the button, function works properly but no result can be shown, as the window reloads. I do not understand this behaviour as there's nothing on the function making it reload, neither is a form submitting.

As consequence of this, the result text is exported to <p id="resultado"></p> but on miliseconds dissapears, as window reloads.

Why this behaviour?

function calcularplazas(){    

        var mensaje = "MENSAJE FINAL";
        document.getElementById("resultado").innerHTML = mensaje;
}
like image 238
Biomehanika Avatar asked Feb 08 '23 06:02

Biomehanika


2 Answers

You say "non-submit" button, but since you haven't given your <button> element a type attribute, it is a submit button by default. You need to tell the browser to treat it as a "normal" button:

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

Clicking this will now not submit the form, and not cause the page to reload.

like image 182
James Thorpe Avatar answered Feb 11 '23 00:02

James Thorpe


You can prevent submit event to be dispatched.

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>

It will works for Return key to do as well

like image 28
Antoine Avatar answered Feb 11 '23 01:02

Antoine