下一个输入框如何确定焦点值

时间:2017-09-18 17:29:13

标签: javascript jquery

我有4个输入框,并且有共同的按键功能:

$(".pincode-input-text").keydown(function(e) {
  if($(this).val()=="") {
    $(this).attr('type','number');
  } else if($(this).val()!="") {
    $(this).attr('type','password');
  }

  // check if input is numeric
  var enteredValue = e.key;

  if ($.isNumeric(enteredValue)) {
    $(this).val(enteredValue);
    $(this).next().attr('type', 'number');
    $(this).next().focus();
    $(this).next().val('');

    $('.fn-mtd_pin_validate').nextAll('span:first').html(" ");
  } else if(!$.isNumeric(enteredValue)) {
    // check if input is non numeric
    $(this).val('');

    if(e.keyCode == 8 || e.key == "Backspace") {
      $(this).prev().focus();
      var elemt = new mtdMobilePin($(window.pinvalidateElemnt).attr('id'));
      elemt.validate();
      return false;
    }

    $(this).focus();
    $('.fn-mtd_pin_validate').nextAll('span:first').html("Invalid Characters");
    $('.fn-mtd_pin_validate').nextAll('span:first').show();
  }

  // Update the value of input type password after value change on any input type.
  var elemt = new mtdMobilePin($(window.pinvalidateElemnt).attr('id'));
  elemt.validate();
});

<span class="fn-mtd_pin_validate">
  <input type="password" min="0" step="1" maxlength="1" autocomplete="off" class="form-control pincode-input-text first mtd_pin_first" tabindex="30">
  <input type="password" maxlength="1" autocomplete="off" min="0" step="1" class="form-control pincode-input-text second mtd_pin_second" tabindex="31">
  <input type="password" maxlength="1" autocomplete="off" min="0" step="1" class="form-control pincode-input-text third mtd_pin_third" tabindex="32">
  <input type="password" maxlength="1" autocomplete="off" min="0" step="1" class="form-control pincode-input-text fourth mtd_pin_fourth" tabindex="33">
</span>

我无法理解,为什么在第一个盒子上输入值后第二个盒子上会出现值。但是我使用的是$(this).next().val('');

1 个答案:

答案 0 :(得分:0)

这里的问题是您需要在keyup事件上发生焦点逻辑,而不是keydown事件。当keydown事件发生时,您将在焦点完成之前移动焦点,以便在您移动它之后完成按键事件。因此,解决它的唯一方法是在键事件完成后执行焦点逻辑。

$(".pincode-input-text").on("keydown", function(e) {
  //backspace logic
}).on("keyup", function(e) {
  //number logic
})