Focus next input once reaching maxlength value(达到 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 值后关注下一个输入
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01