You are hereFocus first Form field with jQuery

Focus first Form field with jQuery


By Gerd Riesselmann - Posted on 19 October 2006

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?

I use something like the following to find the first field in a form:


jQuery.fn.offsetTop = function() {
var e = this.get(0);
if(!e.offsetParent) return e.offsetTop;
return e.offsetTop + $(e.offsetParent).offsetTop();
};

var firstField;

jQuery.each([ 'input', 'select', 'textarea' ], function() {
var field = $(this + ':visible:enabled:first', form).get(0);
if(field)
if(!firstField || $(field).offsetTop() < $(firstField).offsetTop())
firstField = field;
});

Looks like indenting is off in this post, but you get the idea.

Using some of jquery's custom selectors this works a treat.

$("#myform :input:visible:enabled:first").focus();

Impressing.

You can also use
$("input:visible:enabled:first").focus();
to bring focus to any (named or unnamed form) input element.

But I wouldn't have known that if it weren't for your comment. ;)