cancel a submit in jquery?

panchicore picture panchicore · Nov 21, 2009 · Viewed 34.1k times · Source

im doing a form validation and I want to validate the input fields when "on submit" if error Im using jquery.scrollTo to go to error:

$('#form_inscripcion').submit(function() {
    //se traen todos los inputs del formulario
    var $inputs = $('#form_inscripcion :input');

    $inputs.each(function() {
        var encontro_error = validar($(this)); //uses dependence ok
        if (encontro_error){
            $.scrollTo( 'input#'+$(this).attr('id'), 800 ); //go to error
            return false; // dont submit!... but seems not enter here :(
        }
    });

});

The problem is, when error returned doesnt cancel the submit, doesnt run return false; line.

It works OK when

<form id="form_inscripcion" name="form" method="post" action="some" onsubmit="return false">

But so, will never submits. I hope you understand me :) thanks :)

Answer

Doug Neiner picture Doug Neiner · Nov 21, 2009

I would use e.preventDefault() like this:

$('#form_inscripcion').submit(function(e) { 
     //se traen todos los inputs del formulario
     var $inputs = $('#form_inscripcion :input');

     $inputs.each(function() {
        var encontro_error = validar($(this)); //uses dependence ok
        if (encontro_error){
            $.scrollTo( 'input#'+$(this).attr('id'), 800 ); //go to error
            e.preventDefault(); // Cancel the submit
            return false; // Exit the .each loop
        }
     });
});

Just be sure to supply the e parameter to the submit function call (first line in the code block).