Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 393
Heraldmonkey Avatar asked Feb 22 '12 09:02

Heraldmonkey


People also ask

How do you scroll to the first invalid control once a form has been submitted?

To solve the problem in question, you need to perform two things once a form has been submitted: find the first invalid control element, imperatively scroll the container element (e.g. window) so that the control element appears at the top of the viewport.

How do you make a Div follow as you scroll?

just use an background attachment and set it to scroll in your css.

What is Validator error?

A validation error occurs when you have validation/response checking turned on for one of the questions and the respondent fails to answer the question correctly (for numeric formatting , required response).


2 Answers

I dont like all the jQuery extentions so here is my solution to this problem:

if ($('#MYID').valid()) {       //dosomething(); } else {     $('html, body').animate({          scrollTop: ($('.error').offset().top - 300)     }, 2000); } 
like image 41
Thomas Avatar answered Sep 27 '22 22:09

Thomas


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

like image 87
Didier Ghys Avatar answered Sep 27 '22 22:09

Didier Ghys