首页 > 解决方案 > 将焦点移到另一个 div 中的下一个输入

问题描述

我有以下代码:

 <div class="postcode">
    <div>
        <input type="text" maxlength="4">
    </div>
    <div>
        <input type="text" maxlength="4">
    </div>  
</div>

一旦输入了 4 个字符,我需要 Jquery 自动关注下一个输入。我尝试了以下方法,但这仅在输入彼此相邻时才有效:

$(".postcode input").keyup(function () {
    if (this.value.length == this.maxLength) {
      $(this).next('.postcode input').focus();
    }
});

这也意味着当我 shift+tab 时,它会一直关注下一个 div。

最后,如果用户从第二个输入中删除所有字符,我还需要它返回到第一个输入。

标签: jqueryhtml

解决方案


移动到下一个输入

使用parent()选择 parent <div>,移动到next()DIV 和find()child input 以专注于它。请注意,您应该添加:first以便在第一个input.

$(".postcode input:first").keyup(function () {
    if (this.value.length == this.maxLength) {
      $(this).parent().next().find('input').focus();
    }
});

Shift+Tab 保持焦点

添加focus事件以触发相同输入的keyup事件以再次聚焦第二个输入。

$(".postcode input:first").keyup(function () {
    if (this.value.length == this.maxLength) {
      $(this).parent().next().find('input').focus();
    }
}).focus(function(){
    $(this).trigger('keyup');
});

推荐阅读