JQuery script to put focus on first field of any page

13 / Jan / 2011 by Vishal Sahu 3 comments

Hi,

In my recent grails project, i needed to put focus on the first field of any page whenever the page loads. The requirement is such that if the page contains errors then the focus should be on the first input field which has errors.

I searched a lot and with the help of my colleague we came out with a simple JQuery script to put focus on the first input field on any page whenever the page loads.

The script i used is:-

   if (jQuery('.errors').size() > 0) {
       jQuery('input.errors:first').focus();
       jQuery('.errors input:visible:first').focus();
     }
   else {
      jQuery('input:text:visible:first').focus();
    }


I put it in the layout and it works for every gsp which has that layout.

 

It worked for me.
Hope it Helps.

Vishal Sahu
vishal@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. jp

    This is exactly what I’m looking for too. I’ve put it in our main layout but wondering how I get it to execute? do I have to call it from somewhere?

    Reply

Leave a comment -