javascript - 自动跳到下一个空白文本输入框

标签 javascript html

这是我一直在研究的 jsfiddle 示例:

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

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

最佳答案

这应该可以解决问题:

$("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同级。如果找到这样的 sibling ,它将获得焦点。

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

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

关于javascript - 自动跳到下一个空白文本输入框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25704462/

相关文章:

javascript - 用 li 包裹每一行

javascript - 如何在chartjs中绘制高精度数字

javascript - Bookmarklet:转到嵌入 YouTube 页面

javascript - 在 html/jquery 中制作下拉列表,无需遵循任何教程

HTML 内容顶部

javascript - Jquery Datatable 主题隐藏页眉/页脚 balk

javascript - 如何使用 John Papa 风格、Karma 和 Jasmine 数据服务测试 Angular 应用程序?

html - 如何了解/找到基于网络技术的最佳网站

python - 使用lxml在html表中获取href的值

html - 无法让html元素在同一行