jqueryjquery-validatescrollto

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


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. When the form is submitted, validation jumps to the first error and highlights it. To increase usability, I want to scroll to that first error field. But it keeps blowing up the validation entirely or throwing scrollTo errors.

I need to use the standard validation plugin (http://docs.jquery.com/Plugins/Validation) but any scroller would be fine, tho I had been trying with scrollTo (http://flesler.blogspot.com/2007/10/jqueryscrollto.html).

Sample code is at http://jsfiddle.net/DtgKQ/1/, any help is appreciated.


Solution

  • Here's what you can do:

    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