自动跳转到下一个输入

5

我有许多 <input> 标签,它们最多只能接受三个字符,如下所示。

<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 的解决方案。


为什么不使用input事件监听器,并在其中执行您想要的任何逻辑呢? - tomerpacific
4个回答

7

您可以迭代同一类名的元素并检测出两种不同的事件。

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"/>


你好,我正在尝试您的解决方案,但它在表格中无法正常工作,您有什么建议吗?- Fiddle - Kubik Sukenik
因为元素分散在单元格中,所以没有兄弟节点。只需在控制台中阅读错误消息即可。 - djcaesar9114

1
感谢您的提供。
我尝试使用该方法,但在通过键盘导航返回完整输入时遇到了一些问题。首先,我尝试过滤Shift和Tab键,但仍然存在快速按键的问题:当快速释放两个按键时,第一个keyup将移动到下一个输入字段,并且第二个keyup将在我刚刚回到的输入字段上处理。如果该字段也已满,则我只需转到下一个输入(而用户可能想要修改它)。
我使用的解决方案是,如果在输入字段上按键后处理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();

0

djcaesar9114的代码完美运行。我只会为Tab键添加一个例外,因为Tab键已经移动到下一个字段。并在代码中使用maxLength。

if行将如下所示:

if (event.keyCode !== 9 && (event.keyCode === 13 || elt.value.length == elt.maxLength))

0

以下是代码注释。 基本上使用 for 循环遍历输入标签,然后在 keyup 上添加一个 event listener 函数来检查一些条件。我们检查输入属性中设置的最大长度,并将其与值的长度进行比较,还要检查是否按下了“回车键”(即 '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" />


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接