简体   繁体   中英

Javascript: avoiding window to reload

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;
}

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.

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

The button in the form, have you tried giving it type="button" ? Because in a form it gets type="submit" by default (or the form behaves like it would with a submit type).

You Need to make only 2 changes and the code will run .

  1. Put return false in the javascript function.
  2. when you call the function on onclick function write return calcularplazas.

check the below code for for your reference.

function calcularplazas(){    

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM