When form is validated, how to SCROLL to the first error instead of jumping?

后端 未结 6 717
一向
一向 2021-01-30 01:34

I\'ve seen many questions with variations on this theme, but I\'m looking for the straightforward solution:

HTML form, jQuery validation, multiple fields are required. W

6条回答
  •  鱼传尺愫
    2021-01-30 02:01

    Here's what you can do:

    • By default the validate plugin focuses the first erroneous element (in case there's any). Turn off the option focusInvalid by setting it to false.

    • The callback invalidHandler handler is executed when the form is invalid. You get access through the second parameter validator to the validator object and thus to the errorList array. You can then animate the scroll relatively to the first erroneous element.

    Here's the code:

    $("#commentForm").validate({
        focusInvalid: false,
        invalidHandler: function(form, validator) {
    
            if (!validator.numberOfInvalids())
                return;
    
            $('html, body').animate({
                scrollTop: $(validator.errorList[0].element).offset().top
            }, 2000);
    
        }
    });
    

    DEMO

提交回复
热议问题