自动选项卡到下一个空白文本输入框

时间:2014-09-06 20:29:16

标签: javascript html

这是我一直在努力的一个例子:

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);
    });

在上面的示例中,如果我从最左边的文本框开始,如何在字符输入此文本框时将光标前进到下一个空白文本框(而不是下一个填充的文本框) - - 并以其他方式继续使用其他文本框。

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

$("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();
        }
    }
});

它将找到第一个具有空值属性的input兄弟,或根本没有值属性。如果找到这样的兄弟姐妹,它就会得到关注。

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

请注意,我删除了setTimeout函数,因为它似乎没有用,超时为0 ......