jQuery Minute™

…a jQuery Minute™ later and you're done!



Set Focus to the Next Input Field with jQuery

without comments

Setting focus to input fields is easy enough with JavaScript: document.getElementById(‘theInputField’).focus(); but sometimes you need a more generic solution as what happens when the next input field changes ID?

I was recently faced with the problem of setting focus to the next input field. The challenge was that I didn’t know what that field was. So given an input field, find the next logical (in the order of the DOM) input field and set focus. I came up with the following jQuery function (plugin) to accomplish this:

1
2
3
4
5
6
7
8
9
10
$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index + 1 ).focus();
        }
        return false;
    });
};

The use is as follows:

$( 'current_field_selector' ).focusNextInputField();

Let’s break this code down some:

$.fn.focusNextInputField = function() {

Start off by adding a new jQuery function/plugin

return this.each(function() {

Given a set of elements (this => jQuery object), iterate over them (we’ll return false which stop iteration after the first element.)

var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');

Walk up the DOM tree (parents) until we find either the first form element or reach the body tag. Now find all button,input,textarea and select elements.

var index = fields.index( this );

Find out if our current DOM element (this) is in the jQuery collection. Index will return -1 if it is not.

if ( index &gt; -1 &amp;&amp; ( index + 1 ) &lt; fields.length ) {

See if we have a match and make sure we aren’t the last element

fields.eq( index + 1 ).focus();

Select the next input field ( index + 1 ) and set focus to it.

}
return false;

Return false so we stop iteration after this element. So if you call $(…).focusNextInputField() with multiple elements, it will only set focus to the next input field of the first element.

Good luck & enjoy!

Written by jdsharp

May 27th, 2008 at 4:02 pm

Leave a Reply