Cancel feed in jquery?

im does a form check and I want to check the input fields when "on submit" if Im error using jquery.scrollTo to go to the 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 that when an error is returned, it does not cancel the sending, it does not start the line return false;.

It works fine when

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

But it will never obey. I hope you understand me :) thanks :)

+5
source share
2 answers

I would use e.preventDefault()as follows:

$('#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 put the parameter eon the send function call (first line in the code block).

+12
source

#each, #submit. - :

$('#form_inscripcion').submit(function(e) {
        //se traen todos los inputs del formulario
        var $inputs = $('#form_inscripcion :input');
        var returnVal = true;
        $inputs.each(function() {
                var encontro_error = validar($(this)); //uses dependence ok
                if (encontro_error){
                        $.scrollTo( 'input#'+$(this).attr('id'), 800 ); //go to error
                        returnVal = false;
                        return false; // returning false here breaks out of $.each.
                }
        });
        return returnVal;
});

e.preventDefault(), .

+6

All Articles