How to avoid sending a form

1

I want to know how to avoid sending a form. What I need is that if the sum of number2 with number3 is equal to number1 the form is sent but if it is different that the sending of the form stops avoiding the values in the input tags are deleted. Thanks.

 <head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
 <title></title>
  </head>
   <body>
    <form>
     <input  type="number" id="numero1" required>
     <input  type="number" id="numero2" required>
     <input  type="number" id="numero3" required>
     <button  type="submit" >Guardar</button>
   </form>
 <script>
     function evitar_envio_formulario() {
     if (numero1 == numero2 + numero3) {
       //Se envia el formulario
     }else {
       //No se envia el formulario
     }
   }
  </script>
 </body>
    
asked by jufrfa 13.09.2017 в 00:56
source

2 answers

1

You can do it this way.

You start with the button off, to prevent the form from being sent.

You activate it only when the condition is met, listening to the changes occurred in the inputs.

There are comments in the code.

$(function() {
  //De entrada desactivamos el botón
  $("#btnGuardar").prop("disabled", true);
  
  //Aquí escuchamos los cambios en cada input
  $(".myInput").on("change paste keyup", function() {
    var bolDisabled = true;
    var intUno = parseInt($("#numero1").val());
    var intDos = parseInt($("#numero2").val());
    var intTres = parseInt($("#numero3").val());
    var intTotal = intDos + intTres;

    //Evaluamos  y cambiamos o  no  el estado del botón
    if (intTotal == intUno) {
      bolDisabled = false
    }
    $("#btnGuardar").prop("disabled",bolDisabled);

  });

  $("#btnGuardar").click(function() {
      console.log("Acciones al presionar el botón");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input class="myInput" type="number" id="numero1" required>
  <input class="myInput" type="number" id="numero2" required>
  <input class="myInput" type="number" id="numero3" required>
  <button id="btnGuardar">Guardar</button>
</form>
    
answered by 13.09.2017 / 03:44
source
3

You can call the function in the event onsubmit of the form, like this:

<form onsubmit="evitar_envio_formulario()">

And that the function returns true or false according to the case:

function evitar_envio_formulario() {

  var numero1 = document.getElementById('numero1').value;
  var numero2 = document.getElementById('numero2').value;
  var numero3 = document.getElementById('numero3').value;

  if (numero1 == numero2 + numero3) {
    return true;
  } else {
    return false;
  }

}
    
answered by 13.09.2017 в 01:18