0

I have 4 input boxes and there is common key down function:

$(".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>

I am unable to understand, why there is value appeared on second box as soon as value entered on first one. However I am using $(this).next().val('');

Maksim Kalmykov
  • 1,293
  • 3
  • 20
  • 26

1 Answers1

0

The problem here is your logic on focus needs to occur on the keyup event, not the keydown event. When the keydown event occurs you move the focus before it has finished so the keypress event is finishing after you move it. So the only way around it is to do the focus logic after the key event is done.

$(".pincode-input-text").on("keydown", function(e) {
  //backspace logic
}).on("keyup", function(e) {
  //number logic
})
epascarello
  • 204,599
  • 20
  • 195
  • 236