将下一个/上一个输入集中在达到最大长度或退格键上

Focus next/prev input on maxlength reached or backspace keypress

本文关键字:上一个 下一个 输入 集中      更新时间:2023-09-26

我见过HTML表单,其中光标自动从一个输入字段移动到另一个输入字段,并使用退格键移动到上一个字段。在需要粘贴跨多个输入字段的序列号时,或者键入或粘贴在多个字段输入中获取的数字时,它非常有用。

$(document).ready(function() {
  $('.Box').on("keyup", function(e) {
    var Length = $(this).attr("maxlength");
    if ($(this).val().length >= parseInt(Length)) {
      $(this).removeClass("productkey1").addClass("productkey2");
      $(this).next('.Box').focus();
    }
  });
});
$(document).ready(function() {
  $('.Box').on("keydown", function(e) {
    var Length = $(this).attr("maxlength");
    if ($(this).val().length > parseInt(Length)) {
      $(this).removeClass("productkey2").addClass("productkey1");
      $(this).prev('.Box').focus();
    }
  });
});
.Box:focus {
  border: thin solid #FFD633;
  -webkit-box-shadow: 0px 0px 3px #F7BB2E;
  -moz-box-shadow: 0px 0px 3px #F7BB2E;
  box-shadow: 0px 0px 3px #F7BB2E;
}
.Box {
  height: 15px;
  width: 4%;
  text-align: justify;
  letter-spacing: 5px;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
  <sapn>Enter Key Code :</sapn>
  <input class="Box productkey1" style="width: 35px;" type="password" name="number1" maxlength="1">
  <input class="Box productkey1" style="width: 35px;" type="password" name="number2" maxlength="1">
  <input class="Box productkey1" style="width: 35px;" type="password" name="number3" maxlength="1">
  <input class="Box productkey1" style="width: 35px;" type="password" name="number4" maxlength="1">
</div>

您可以通过在按下退格键时检查当前输入中文本的length是否为零来实现此目的:

$(document).ready(function() {
  $('.Box').on("keyup", function(e) {
      var $input = $(this);
      if ($input.val().length == 0 && e.which == 8) {
        $input.toggleClass("productkey2 productkey1").prev('.Box').focus();
      }
      else if ($input.val().length >= parseInt($input.attr("maxlength"), 10)) {
        $input.toggleClass("productkey1 productkey2").next('.Box').focus();
      }
  });
});
.Box:focus {
  border: thin solid #FFD633;
  -webkit-box-shadow: 0px 0px 3px #F7BB2E;
  -moz-box-shadow: 0px 0px 3px #F7BB2E;
  box-shadow: 0px 0px 3px #F7BB2E;
}
.Box {
  height: 15px;
  width: 50px;
  text-align: justify;
  letter-spacing: 5px;
  /*CSS letter-spacing Property*/
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
  <sapn>Enter Key Code :</sapn>
  <input class="Box productkey1" type="password" name="number1" maxlength="4">
  <input class="Box productkey1" type="password" name="number2" maxlength="4">
  <input class="Box productkey1" type="password" name="number3" maxlength="4">
  <input class="Box productkey1" type="password" name="number4" maxlength="4">
</div>

另请注意,我将on()逻辑整理到单个事件处理程序中,并使用toggleClass()在单个调用中修改这两个类。