HippoDuck
HippoDuck

Reputation: 2194

Unable to set focus to the next text box

I have three text boxes all with the class "initialbox".

The max length for each box is 1 character. When a box has been filled with one character, the next box should be set as focus. (The exact same way that using the TAB key would work).

I added the alert() in order to check that the event if firing, and it is, but the $(this).next('.initialbox').focus() doesn't set the focus to the next tab. I have tried also using $(this).next.focus().

Many thanks.

HTML:

<table style="width:100%;">
    <tr>
        <td style="width:33.3%">
            <input type="text" class="initialbox" maxlength="1" size="1" id="firstinitial" />
        </td>
        <td style="width:33.3%">
            <input type="text" class="initialbox" maxlength="1" size="1" id="secondinitial" />
        </td>
        <td style="width:33.3%">
            <input type="text" class="initialbox" maxlength="1" size="1" id="thirdinitial" />
        </td>
    </tr>
    <tr>
        <td style="width:33.3%">1st Initial</td>
        <td style="width:33.3%">2nd Initial</td>
        <td style="width:33.3%">3rd Initial</td>
    </tr>
</table>

JQuery:

$(".initialbox").keyup(function () {
    if (this.value.length == 1) {
        alert();
        $(this).next('.initialbox').focus();
    }
});

JSFiddle: http://jsfiddle.net/v9y51pds/1/

Upvotes: 2

Views: 353

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

An alternative to traversing up and down the DOM is to grab the index of the input within the $('.initialbox') collection.

You can then go directly to the next input like this:

$('.initialbox').keyup(function() {
  var idx= $('.initialbox').index(this);
  if(this.value.length == 1) {
    $('.initialbox').eq(idx+1).focus();
  }
});

Fiddle

Upvotes: 1

Ted
Ted

Reputation: 14927

Try this instead (for the code in your fiddle):

$(".initialbox").keyup(function () {
    if (this.value.length == 1) {
        $(this).parent('td').next('td').find('.initialbox').focus();
    }
});

See it work here

The problem was $(this).next() is looking at siblings, not the entire dom. So you need to traverse the dom to find the element you want to focus next.

(edited to add 'td' to the .parent() and .next() bits to make it clearer what's going on)

Upvotes: 3

George
George

Reputation: 36786

You can't use .next() with your markup, because your .initialbox input elements aren't siblings.

You need to traverse to the parent (closest()) <td>, along to it's neighbour <td> and then find the .initialbox within:

$(".initialbox").keyup(function () {
    if (this.value.length == 1) {
        alert();
        $(this).closest('td').next('td').find('.initialbox').focus();
    }
});

Upvotes: 8

Related Questions