1. Overview

Challenge & starter files: Advent of JS

Full codes: nilstarbb/advent-of-js/10-4-digit-code

Live Demo: 11 - Four Digit Code || Advent of JavaScript

Preview:

digit-code.gif

2. Details

Users should be able to:

  • type in a digit and automatically be taken to the next input
  • paste in a 4 digit code

3. Coding

逻辑如下:

  • 当 input value 的 length 达到上限(maxlength="1")时,自动 focus 到下一个 input。
  • 对 input 进行粘贴时,将粘贴的字符串拆成单独的字符数组,用循环按序设置为 input 的 value。(详见:Element: paste event - Web APIs | MDN

额外的 validation:

  • 只允许非空白值或数字粘贴。

完整代码:

const autoFocus = (e) => {
  if (e.target.value.length == 1 && e.target.nextElementSibling) {
    e.target.nextElementSibling.focus();
  }
};

const autoPaste = (e) => {
  e.preventDefault();
  // const pasteVal = e.clipboardData.getData("text").replace(/\s+/g, '').split(""); // remove whitespace
  const pasteVal = e.clipboardData.getData("text").replace(/\D/g,'').split(""); // remove non-numeric
  let currentInput = e.target;
  let i = 0;
  while (currentInput && pasteVal[i]) {
    currentInput.value = pasteVal[i];
    i++;
    currentInput = currentInput.nextElementSibling;
  }
};

const inputs = document.querySelectorAll('input[type="text"');

inputs.forEach((input) => {
  input.onkeyup = autoFocus;
  input.onpaste = autoPaste;
});