Javascript将输入移动到另一个输入

时间:2018-01-16 08:22:00

标签: javascript php

想问一下..假设我有3个输入示例,其中字符的最大长度不同。

enter image description here

<input type="text" name="text1">
<input type="text" name="text2">
<input type="text" name="text3">

如果我输入字符123456789,那么当我在第一个输入中填入数字12时,会自动移动到第二个输入。如何 ?还是javascript名称?

enter image description here

1 个答案:

答案 0 :(得分:3)

这是一个非常干净的实现,您需要:

  • 从maxlength属性读取。
  • 缩放到容器内的任意数量的输入。
  • 自动查找要关注的下一个输入。

http://jsfiddle.net/4m5fg/5/

<div class="container">
a: <input type="text" maxlength="5" />
b: <input type="text" maxlength="5" />
c: <input type="text" maxlength="5" />
</div>
..

var container = document.getElementsByClassName("container")[0];
container.onkeyup = function(e) {
    var target = e.srcElement || e.target;
    var maxLength = parseInt(target.attributes["maxlength"].value, 10);
    var myLength = target.value.length;
    if (myLength >= maxLength) {
        var next = target;
        while (next = next.nextElementSibling) {
            if (next == null)
                break;
            if (next.tagName.toLowerCase() === "input") {
                next.focus();
                break;
            }
        }
    }
    // Move to previous field if empty (user pressed backspace)
    else if (myLength === 0) {
        var previous = target;
        while (previous = previous.previousElementSibling) {
            if (previous == null)
                break;
            if (previous.tagName.toLowerCase() === "input") {
                previous.focus();
                break;
            }
        }
    }
}

来源:Focus next input once reaching maxlength value