达到 maxlength 值后关注下一个输入

Focus next input once reaching maxlength value(达到 maxlength 值后关注下一个输入)

本文介绍了达到 maxlength 值后关注下一个输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前一个输入达到其最大长度值后,如何聚焦下一个输入?

How can I focus the next input once the previous input has reached its maxlength value?

a: <input type="text" maxlength="5" />
b: <input type="text" maxlength="5" />
c: <input type="text" maxlength="5" />

如果用户粘贴的文本大于最大长度,理想情况下它应该溢出到下一个输入中.

If a user pastes text that is greater than the maxlength, ideally it should spill into the next input.

jsFiddle: http://jsfiddle.net/4m5fg/1/

我必须强调我想使用插件,因为我更愿意学习其背后的逻辑,而不是使用已经存在的东西.感谢理解.

I must stress that I do not want to use a plugin, as I'd much rather learn the logic behind this, than use something that already exists. Thanks for understanding.

推荐答案

没有使用 jQuery 并且是一个非常干净的实现:

No jQuery used and is a very clean implementation:

  • 从 maxlength 属性中读取.
  • 可扩展到容器内任意数量的输入.
  • 自动查找下一个要关注的输入.
  • 没有 jQuery.

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;
            }
        }
    }
}

这篇关于达到 maxlength 值后关注下一个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:达到 maxlength 值后关注下一个输入

基础教程推荐