Focus first Form field with jQuery

I somehow like the jQuery JavaScript library. Have a look at the jQuery code for the Zebra-Table-Showdown: Ain’t this a beauty?

However, when it comes to focusing the first (visible) field on a form, things are not that elegant. I got it working, though. Here’s my current attempt:

// Focus first element

$.fn.focus_first = function() {
  var elem = $('input:visible', this).get(0);
  var select = $('select:visible', this).get(0);
  if (select && elem) {
    if (select.offsetTop < elem.offsetTop) {
      elem = select;
    }
  }
  var textarea = $('textarea:visible', this).get(0);
  if (textarea && elem) {
    if (textarea.offsetTop < elem.offsetTop) {
      elem = textarea;
    }
  }
  
  if (elem) {
    elem.focus();
  }
  return this;
}

Use it like this:

$(window).load(function() {
  $('form').focus_first();
);

I wonder, though, if there is a more comprehensive expression to find the first element of either type “input”, “select”, or “textarea”.

$('input:visible,select:visible,textarea:visible', this).eq(0)

will not work, since it will always return the first “input”, regardless if there is a “select” or “textarea” before it.

Any suggestions?

Published: October 19 2006