为了提高我正在构建的信用卡表单的可用性,我希望浏览器在用户输入 maxlength
属性中允许的字符后将焦点移至下一个输入输入
。
目前,我已经使用三个输入字段完成了此操作,但采用的方式非常笨重,无法扩展。请参见下面的代码。
我想做的是编写以下脚本:
If an input with the class autotab has reached it maxlength, move the focus to the next closest input of any class. Additionally (what I have not yet accomplished in my code below) if the value of an input with the class autotab is empty/null, and the backspace/delete key is pressed, the focus should move to the previous closest input of any class`
我的目标是摆脱对为特定字段编写变量的依赖,并稍微自动化此过程。
$( document ).ready(function() {
var CCCardFill = 0;
var CCExpMonthFill = 0;
var CCExpYearFill = 0;
var CCCardMax = 16;
var CCExpMonthMax = 2;
var CCExpYearMax = 4;
$( "input" ).keyup(function() {
var CCCardFill = $(".CCCard").val().length;
var CCExpMonthFill = $(".CCExpMonth").val().length;
var CCExpYearFill = $(".CCExpYear").val().length;
if (CCCardFill >= CCCardMax) {
$(".CCExpMonth").focus();
}
if (CCExpMonthFill >= CCExpMonthMax) {
$(".CCExpYear").focus();
}
if (CCExpYearFill >= CCExpYearMax) {
$(".CCName").focus();
}
});
});
最佳答案
您可以使用 maxLength
和 value.length
属性。当它达到最大长度时,您可以简单地使用 next().focus()
聚焦下一个项目。
$( "input[maxlength]" ).keyup(function() {
var maxLen = this.maxLength;
var currentLen = this.value.length;
if (maxLen === currentLen)
{
$(this).next().focus();
}
});
如果您的 input
之间还有其他 HTML 元素,您可以使用 nextAll("input").first()
获取最接近的元素与此之后的选择器匹配的元素:
$(this).nextAll("input").first().focus();
关于javascript - 如何在每个输入达到最大长度时自动推进焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250898/