【问题标题】:Move focus to next input in another div将焦点移到另一个 div 中的下一个输入
【发布时间】:2020-04-02 18:25:23
【问题描述】:

我有以下代码:

 <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。

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

【问题讨论】:

标签: jquery html


【解决方案1】:

移动到下一个输入

使用parent() 选择父&lt;div&gt;,移动到next() DIV 和find() 子输入以专注于它。请注意,您应该添加 :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');
});

【讨论】:

  • 这完全可以正常工作,谢谢!我该如何做相反的事情,以便当第二个框中的字符数变为 0(或者当它为零并且用户按下退格键时)时,焦点又回到第一个?
【解决方案2】:

为每个输入尝试此代码,并将所有代码添加到文档读取函数中:

  <script>
   $(document).ready(function(){
    $("#id1").keyup(function () {
  if (this.value.length == this.maxLength) {
  $('#id2').focus();
  }
  });
  });
  </script>
  <div class="postcode">
  <div>
    <input id="id1" type="text" maxlength="4">
  </div>
  <div>
    <input id="id2" type="text" maxlength="4">
  </div>  
 </div>

【讨论】:

    【解决方案3】:

    这是我使用的解决方案(部分由 Alon Pini 建议):

    jQuery(function($) {
    
        // Tab to next item when maxlength is reached
        $(".postcode div:nth-child(1) input").keyup(function () {
            if (this.value.length == this.maxLength) {
                $(this).parent().next().find('input').focus();
            }
        });
    
        // Tab to previous item when pressing backspace and character count is 0
        $("postcode div:nth-child(2) input").on('keyup', function(e) {
            if(e.which==8) {
                if (this.value.length == 0) {
                    $(this).parent().prev().find('input').focus();
                }
            }
        });
    
    });
    

    此解决方案同时进行,当字符数达到最大长度时关注下一项,并在第二个输入字段中的字符数达到零时关注前一项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 2011-01-28
      相关资源
      最近更新 更多