fordie’s Blog

28 Oct, 2008

Scroll to the first error in form – using jQuery

Posted by: admin In: css|jQuery|usability|web development|work

Oftentimes we ask our users to provide us with an awful lot of information in things like registration forms. It’s no wonder that every now and again the poor dears forget to fill in a box or make a mistake.

On longer or complex forms users can find it difficult to see where the errors actually are.

The other week our QA manager asked us (the front end team) to scroll to the first error on a page. I started off thinking that it was going to be difficult and time consuming to achieve, but with the awesomeness of jQuery & one little-bitty plugin I was able to achieve the desired effect in  3 or 4 lines of code.

This technique relies on you already having validated your form and added a class of “error” to you the markup, either on the form elements or an error message.

You will need

  • jQuery
  • The scrollTo plugin (I used the minified version)
  • A web page with some errors on it
  • a couple of old yoghurt pots and some sticky back plastic.

And here’s the code

add this to the head of your document:

    <script type="text/javascript" src="/JQuery.js"></script>
    <script type="text/javascript" src="/jquery.scrollTo-min.js">
    </script>

    <script type="text/javascript">
        $(document).ready(function() {
            $(".error:first").attr("id","firstError");
            $("#firstError").each(function (){
                $.scrollTo("#firstError", 800);
            });
        });
    </script>

And Bob’s your uncle!

Please let me know if you found this technique useful.


Incidentally the code for this post was prepared with the very excellet postable. Check it out!

  • http://thinkdrastic.net/ Olly

    Oooh, interesting. I wonder if we could use this to modify .net validation summaries so clicking the error scrolls to the relevant form field…

fordie, elsewhere:

if you're an internet stalker these would be good sites for you to stalk me on…