Sunday, February 15, 2009

Focus First Form Field with JQuery

It tok me a while to find this little gem and polish it up a bit so I figured I would pass it on. The title of the post should be enough of a desciption of what I was trying to do so here is the code.
function FocusFirstField() {
var topIndex = null;

var fields = $("input:visible:enabled:first,

if (fields.size() > 0)
topIndex = 0; 

for (var i = 1; i < fields.size(); i++)
if (fields[i].offsetTop < fields[topIndex].offsetTop)
topIndex = i;

if (topIndex != null)

The first line just defines a variable to hold the index of the control we finally identify as the top most field in the form.

The second line uses JQuery to select the first, visible, enabled of each input, select and textarea html elements.

The third section primes the following loop. It checks to see that at least one element has been returned and sets the topIndex value to 0.

The fourth section of code loops through any other elements that have been returned and compares the offsetTop value of each to determine the top most element.

The last line of the function checks to see if any element of the selector types has been found and sets the focus to the element found to be the top most.

The function is best called from the window load event as the JQuery document ready event fires too early on some browsers:

And the selector can obviously be tailored to fit your needs.

-- EDIT:

One of the things that I just noticed about this is that I tried to make the code smart enough to take just about any CSS into consideration, hence the loop checking top offsets.  What I just noticed is that the ':first' selectors might work against this at times.  I included those selectors to limit the number of DOM elements returned, but it may cause things to not work all the time.

I think in most situations the code should be fine, but if your CSS really moves elements around ala CSS Zen Garden, you might need to remove the :first portion of each phrase in the selector.

1 comment:

  1. great thanks! Saved me hours working it out myself.