【问题标题】:jQuery automatically move to next input with max reach valuejQuery 自动移动到具有最大到达值的下一个输入
【发布时间】:2020-11-02 10:29:26
【问题描述】:

我想用最后一个值移动到下一个输入。例如,我想输入信用卡号,如果数字大于 4,则每个数字的最大容量为 4 位,然后它将自动移动到具有最后一个附加值的下一个输入。

例如我想添加 12345,所以这里 1234 将添加到第一个输入,而 5 将自动移动到下一个输入。

1234 5

我已经尝试使用以下方式,自动移动到下一个字段是工作但不移动最后一个值。

$("#card3").bind("keypress", function (e) {
        var error = [];         
        var card3 =$("#card3").val();
        
        if ( card3.length > 3  ) {
                error.push('<p>Allow digits only(0 - 4).</p>');
                if (this.value.length == this.maxLength) {              
                  $('#card4').focus();
                }
        }

我要添加 12345,所以 5 会自动移动到下一个输入。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

修改欺骗https://stackoverflow.com/a/40221557/295783 来处理粘贴

如果您不需要处理粘贴,那么骗子将为您工作,因为您无法在没有最大值后的数字进入下一个字段

通过在第一个字段中粘贴 16 位数字或一次输入一个数字来测试以下内容

$("[data-max]").eq(0).on("input", function() {
  const val = this.value;
  if (val.length === 16) {
    const re = new RegExp(`.{${4}}`, "g")
    const chunks = val.match(re)
    chunks.forEach((chunk, i) => $("[data-max]").eq(i).val(chunk))
  }
})
$("[data-max]").on("input", function() {
  if (this.value.length >= this.dataset.max) {
    if (this.nextElementSibling) this.nextElementSibling.focus();
  }
})
$("[data-max]").last().on("input", function() {
  this.value = this.value.slice(0, 4)
})
[data-max] {
  width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" data-max="4" />
<input type="text" data-max="4" />
<input type="text" data-max="4" />
<input type="text" data-max="4" />

【讨论】:

    【解决方案2】:

    这就是问题所在

    if (this.value.length == this.maxLength) {              
                      $('#card4').focus();
                    }
    

    this.maxLength 返回 undefined 因此该块永远不会运行。 试试

    if (this.value.length == 4) {              
                      $('#card4').focus();
                    }
    

    您可能希望从输入属性中添加和检索 maxLength 值

    <input data-max-length="4" />
    
    if (this.value.length == $(this).data('max-length')) {              
                      $('#card4').focus();
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 2021-11-02
      • 2013-07-30
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多