【问题标题】:Moving to next input automatically自动移动到下一个输入
【发布时间】:2025-12-30 15:05:12
【问题描述】:

我有很多<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"/>

我们可以:

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

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

【问题讨论】:

标签: javascript html input


【解决方案1】:

您可以遍历具有相同类名的元素并检测两个不同的事件。

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()
    }
  });
})
<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"/>

【讨论】:

    【解决方案2】:

    谢谢。

    我接受了,但在通过键盘导航返回完整输入时遇到了一些问题。 首先,我尝试过滤 Shift 和 Tab 键,但我仍然遇到快速击键的问题:当快速释放两次击键时,第一个键移动到下一个输入字段,第二个键在我刚回来的输入字段上处理到。如果该字段也已满,那么我只需传递到下一个输入(而用户可能想要修改它)。

    我使用的解决方案包括,如果在输入字段上按下某个键后处理 keyup,则移至下一个输入。 我还分离了侦听器的逻辑,测试移动条件(在本例中:输入和字段完成)并移动到下一个输入。

    var setChangeInputWhenComplete = function() {
        document.getElementsByTagName("input").forEach(elt => {
            // Variable to trace if a key has been pressed on input since arriving on it
            var keyPressed = false;
    
            // Records if a key has been pressed on input field in order not to pass to next field if the keyup event occurs on a field we've juste arrived on
            elt.addEventListener("keypress", function(event) {
                keyPressed = true;
            });
            
            // Clears previous keypressed recording when we come back on input field
            elt.addEventListener("focus", function(event) {
                keyPressed = false;
            });
            
            elt.addEventListener("keyup", function(event) {
                // When quickly releasing a second key, pressed on previous field, when arriving on a new field, we should not pass to next field even if the field is already full
                if (keyPressed) {
                    // If field is full, pass to next input
                          if (mustMoveToNextInput(event)) {
                              moveToNextInput(event);
                          }
                }
            });
        });
    };
    
    var moveToNextInput = function(event) {
        //set variable for next
        var next = event.srcElement;
        //loop for the next element of the inputField
        while (next = next.nextElementSibling) {
          //conditional if the next is not present, so last element we break the code
          if (next == null)
            break;
          //conditional to for the next element that is actually an input tag
          if (next.tagName.toLowerCase() == "input") {
            next.focus();
            break;
          }
        }
    };
    
    var mustMoveToNextInput = function(event) {
      var inputField = event.srcElement;
      var maxLength = parseInt(inputField.attributes["maxlength"].value, 10);
      
      return (event.keyCode === 13 || inputField.value.length >= maxLength);
    };
     
    setChangeInputWhenComplete();
    

    【讨论】:

      【解决方案3】:

      下面代码中的注释。 基本上for 循环遍历输入标签,然后在keyup 上使用event listener 函数来检查一些条件。我们检查输入属性中设置的 maxlength 并根据值长度检查它,我们还检查是否按下了 'enterkey aka '13。下一个兄弟元素的 While 循环。在设置 nextElementSibling 时使用 null 检查元素是否在最后一个元素上。

      var container = document.getElementsByTagName("input");
      // for loop to iterate through elements
      for (let i = 0; i < container.length; i++) {
        // create function event for keyup in input fields
        container[i].onkeyup = function(e) {
          //create variable for events source element
          var target = e.srcElement;
          //create variable for the max length attribute in the input field
          var maxLength = parseInt(target.attributes["maxlength"].value, 10);
          //create variable for the length of the targets value in the input
          var myLength = target.value.length;
          //conditional that sees if the elements value is equal tot he maxlength value 
          //or if the enter key is pressed
          if (e.keyCode === 13 || myLength >= maxLength) {
            //set variable for next
            var next = target;
            //loop for the next element of the target
            while (next = next.nextElementSibling) {
              //conditional if the next is not present, so last element we break the code
              if (next == null)
                break;
              //conditional to for the next element that is actually an input tag
              if (next.tagName.toLowerCase() == "input") {
                next.focus();
                break;
              }
            }
          }
        }
      }
      <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" />

      【讨论】:

        最近更新 更多