mtcrts70
mtcrts70

Reputation: 35

Auto tab to next blank text input box

Here is a jsfiddle example I've been working on:

http://jsfiddle.net/4m5fg/143/

HTML:

<input type="text" maxlength="1" size="1"/>
<input type="text" maxlength="1" value="e" tabindex="-1" size="1" readonly />
<input type="text" maxlength="1" size="1"/>
<input type="text" maxlength="1" value="r" tabindex="-1" size="1" readonly />
<input type="text" maxlength="1" size="1"/>

JS:

 $("input").bind("input", function() {
        var $this = $(this);
        setTimeout(function() {
            if ( $this.val().length >= parseInt($this.attr("maxlength"),10) )
                $this.next("input").focus();
        },0);
    });

In the above example, if I'm starting at the leftmost textbox, how can I make it so when the character is entered into this textbox the cursor advances to the next blank textbox (not the next filled in textbox)---and have it continue on in this manner for other textboxes.

Upvotes: 0

Views: 1166

Answers (1)

Pevara
Pevara

Reputation: 14310

This should do the trick:

$("input").on("input", function () {
    var $this = $(this);
    if ($this.val().length >= parseInt($this.attr("maxlength"), 10)) {
        var nextEmpty = $this.nextAll("input[value=''], input:not([value])")[0];
        if (nextEmpty) {
            nextEmpty.focus();
        }
    }
});

It will find the first input sibling with an empty value attribute, or no value attribute at all. If such a sibling is found, it will get focus.

http://jsfiddle.net/4m5fg/149/

Note that I removed the setTimeout function as it seems to be of no use with a timeout of 0...

Upvotes: 2

Related Questions