8

In jQuery, how can I trigger the behavior of a user tabbing to the next input field?

I've tried this:

var e = jQuery.Event("keydown");
e.which = 9; // # Key code for the Tab key
$("input").trigger(e);

But triggering the event doesn't move the cursor to the next field.

I suppose I could move the cursor manually using focus(), but deciding which field should be next is something the browser already knows how to do, so it seems much cleaner to just trigger a tab.

Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nathan Long
  • 122,748
  • 97
  • 336
  • 451

4 Answers4

6

Here's one solution, via http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/

$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find(':input').not('[type=hidden]');
        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();
Yardboy
  • 2,777
  • 1
  • 23
  • 29
3

See the accepted answer to this question. If for example you want to move focus to the next field when a certain number of characters have been entered, you could use that code in the keyup event, and check the entered number of characters.

The code in that answer works by getting the set of inputs in the form, finding the selected input and adding 1 to the index of the selected input, and then triggering the focus event on the element with that index.

Community
  • 1
  • 1
James Allardice
  • 164,175
  • 21
  • 332
  • 312
2

There's a JQuery plugin available:

http://www.mathachew.com/sandbox/jquery-autotab/

laffuste
  • 16,287
  • 8
  • 84
  • 91
0

Have you tried using

$("input").trigger( 'keypress', e );

as a solution?
I find sometimes being explicit is best. If that doesn't work possibly even

$("input").trigger( 'keypress', [{preventDefault:function(){},keyCode:9}] );.

Hope this helps.

JimP
  • 1,070
  • 15
  • 26
  • Simulating key press wont work, https://stackoverflow.com/questions/32428993/why-doesnt-simulating-a-tab-keypress-move-focus-to-the-next-input-field – Rohith K D Jul 12 '18 at 12:51