How to avoid page redirection in an alert with Javascript and jQuery?

8

When I show a JS alert, it redirects me to the start of my page and all the information in a form is lost and what I want is to show the alert but not redirect or recharge. How can I avoid redirecting, after accepting the alert ?, the alert is the common, so I have not added any parameters

    $("#btnagregarSIM").click(function() {

      var cantidadTotalSim = $("#txtValorTotalSim").val();
      var cantidadArticulo = $("#txtValorTotalArticulo").val();
      var facturaSim = $("#txtFacturaSIM").val();
      var cantidadSim = $("#txtCantidadsim").val();
      var idSim = $("#cmbSim").val();
      var descripcionSim = $("#cmbSim option:selected").html();

      var x = parseFloat(cantidadTotalSim) + parseFloat(cantidadSim);

      if (x <= cantidadArticulo) {
        if (cantidadTotalSim <= cantidadArticulo) {
          fn_agregarSIM(facturaSim, cantidadSim, idSim, descripcionSim);
        } else {
          alert("Revisa que la cantidad de SIM sea la misma que la cantidad de Articulos")
        }
      } else {
        alert("La cantidad de SIM no puede ser mayor que la cantidad total de articulos.");
      }

    });
    
asked by Ivxn 10.06.2016 в 23:52
source

3 answers

5

An alert should not redirect you, what can happen is that the "#btnagregarSIM" button is a submit and this automatically executes the sending of the associated form.

for which you should add the call to preventDefault in the click function as follows

 $("#btnagregarSIM").click(function(event) {

    ...

    if (x <= cantidadArticulo) {
        if (cantidadTotalSim <= cantidadArticulo) {
            fn_agregarSIM(facturaSim, cantidadSim, idSim, descripcionSim);

        } else { 
            alert("Revisa que la cantidad de SIM sea la misma que la cantidad de Articulos");
            event.preventDefault();
        }
    } else { 
        alert("La cantidad de SIM no puede ser mayor que la cantidad total de articulos.");
        event.preventDefault();
    }
  }
    
answered by 10.06.2016 / 23:57
source
1

You must check that the #btnagregarSIM button is not a submit type. In this case you have to remove the "form" tag or just change the button with a "a" label.

    
answered by 11.06.2016 в 00:08
0

According to the Jquery documentation, you must use the preventDefault method to prevent the event from calling to follow its normal behavior.

link

$( "a" ).click(function( event ) {
  event.preventDefault();
  $( "<div>" )
    .append( "default " + event.type + " prevented" )
    .appendTo( "#log" );
});
    
answered by 11.06.2016 в 01:01