自动移至下一个输入

fla*_*ame 6 html javascript input

我有很多<input>s 最多接受三个字符,如图所示。

<input type="text" id="0" maxlength="3"/>
<input type="text" id="1" maxlength="3"/>
<input type="text" id="2" maxlength="3"/>
<input type="text" id="3" maxlength="3"/>
Run Code Online (Sandbox Code Playgroud)

我们可以吗:

  • 允许用户通过按键移动文本框Enter
  • 输入三个或更多字符后自动将用户移动到下一个文本框?

我使用 JQuery 看到了一些关于这个主题的问题,但如果可能的话,我正在寻找一种专门的 JavaScript 解决方案。

djc*_*114 9

您可以迭代相同类名的元素并检测两个不同的事件。

var elts = document.getElementsByClassName('test')
Array.from(elts).forEach(function(elt){
  elt.addEventListener("keyup", function(event) {
    // Number 13 is the "Enter" key on the keyboard
    if (event.keyCode === 13 || elt.value.length == 3) {
      // Focus on the next sibling
      elt.nextElementSibling.focus()
    }
  });
})
Run Code Online (Sandbox Code Playgroud)
<input type="text" class="test" id="0" maxlength="3"/>
<input type="text" class="test" id="1" maxlength="3"/>
<input type="text" class="test" id="2" maxlength="3"/>
<input type="text" class="test" id="3" maxlength="3"/>
Run Code Online (Sandbox Code Playgroud)