【问题标题】:Autofocus onto next input after maxlength has been met达到 maxlength 后自动聚焦到下一个输入
【发布时间】:2021-11-02 13:36:12
【问题描述】:

我希望设置一个标准 DOB 问题,一旦用户满足 maxlength 要求,它将自动关注下一个输入(即月份字段)。

但是,我当前的方法不会自动聚焦到下一个字段上?

$(function() {

  $(".input").keyup(function() {
    if (this.value.length == this.maxLength) {
      console.log(this.maxLength);
      var $next = $(this).next('.input');
      if ($next.length)
        $(this).next('.input').focus();
      else
        $(this).blur();
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="question question--1">
  <input class="input" type="number" data-format="day" placeholder="DD" maxlength="2" />
</div>

<div class="question question--2">
  <input class="input" type="number" data-format="month" placeholder="MM" maxlength="2" />
</div>

<div class="question question--3">
  <input class="input" type="number" data-format="year" placeholder="YYYY" maxlength="4" />
</div>

我认为问题可能是因为下一个 .input 在另一个父元素中。我尝试将其调整为以下内容:

var $next = $(this).parent(".question").next('.input');

但结果还是一样。

【问题讨论】:

标签: javascript html jquery


【解决方案1】:

检查$next = $(this).parent('div').next('div').find('.input'); 的长度并关注.input 使用$next 而不是$(this).next('.input')

例子:

$(function() {
  $(".input").keyup(function() {
    if (this.value.length == this.maxLength) {
      var $next = $(this).parent('div').next('div').find('.input');
      if ($next.length) {
        $next.focus();
      } else {
        $(this).blur();
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="question question--1">
  <input class="input" type="number" data-format="day" placeholder="DD" maxlength="2" />
</div>

<div class="question question--2">
  <input class="input" type="number" data-format="month" placeholder="MM" maxlength="2" />
</div>

<div class="question question--3">
  <input class="input" type="number" data-format="year" placeholder="YYYY" maxlength="4" />
</div>

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 2012-01-09
    • 2013-03-13
    • 2023-04-07
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多