cancel a submit in jquery?

前端 未结 2 961
终归单人心
终归单人心 2021-01-05 07:48

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         


        
相关标签:
2条回答
  • 2021-01-05 08:36

    You are returning from #each function, not #submit. Do something like this instead:

    $('#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;
    });
    

    You could also do e.preventDefault() to stop the form from being submitted.

    0 讨论(0)
  • 2021-01-05 08:39

    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).

    0 讨论(0)
提交回复
热议问题