jQuery 验证后,自动选项卡到下一个输入字段不起作用 类似这样:.nextAll('.otp-btn').first() 而不是 .next('.otp-btn')

问题描述

我有 3 个如下所示的文本框,我想将 autotab 添加到此输入字段,并且正在工作。当验证到来时,即在验证错误之后,自动选项卡功能不起作用。当这些输入为空时,验证将起作用,并将根据需要关注红色,当时我看不到自动选项卡功能。请帮我解决这个问题。

<input type="text" name="otp1" id= "otp1" class="otp-btn" maxlength="1">
<input type="text" name="otp2" id= "otp2" class="otp-btn" maxlength="1">
<input type="text" name="otp3" id= "otp3" class="otp-btn" maxlength="1">

 $(document).ready(function () {
    $("#updatePassForm input:text").first().focus();
    $(".otp-btn").keyup(function (e) {
    e.preventDefault();
    if (this.value.length == this.maxLength) {
      $(this).next('.otp-btn').focus();
    }
}); 

    $('#updatePassForm').validate({
      rules: {
        otp1: {
          required: true,},otp2: {
          required: true,otp3: {
          required: true,messages: {
        otp1: {
          required: '',otp2: {
          required: '',otp3: {
          required: '',submitHandler: function (form) {
}
});

解决方法

原因是,jQuery选择器的next函数获取紧随其后的兄弟项。因此,当验证显示 next 引用由 jquery et 生成的错误标签时,因为它没有 css 类 otp-btn,它没有被聚焦。

因此,解决方案是将具有类 otp-btn 的所有后续元素同级,然后检索第一个元素。

类似这样:.nextAll('.otp-btn').first() 而不是 .next('.otp-btn')