我有以下代码:
<div class="postcode">
<div>
<input type="text" maxlength="4">
</div>
<div>
<input type="text" maxlength="4">
</div>
</div>
输入4个字符后,我需要Jquery自动关注下一个输入。我已经尝试了以下方法,但这仅在输入彼此相邻的情况下有效:
$(".postcode input").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.postcode input').focus();
}
});
这也意味着当我按住shift键和Tab键时,它会继续关注下一个div。
最后,如果用户从第二个输入中删除所有字符,我还需要它返回到第一个输入。
答案 0 :(得分:0)
使用parent()
选择父项<div>
,移至next()
DIV,然后find()
子项输入以专注于它。请注意,您应该添加:first
才能在第一个input
上应用该功能。
$(".postcode input:first").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).parent().next().find('input').focus();
}
});
添加focus
事件以触发同一输入的keyup
事件以再次聚焦第二个输入。
$(".postcode input:first").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).parent().next().find('input').focus();
}
}).focus(function(){
$(this).trigger('keyup');
});
答案 1 :(得分:0)
尝试使用此代码为每个输入ID,并将所有代码添加到文档读取功能中:
<script>
$(document).ready(function(){
$("#id1").keyup(function () {
if (this.value.length == this.maxLength) {
$('#id2').focus();
}
});
});
</script>
<div class="postcode">
<div>
<input id="id1" type="text" maxlength="4">
</div>
<div>
<input id="id2" type="text" maxlength="4">
</div>
</div>
答案 2 :(得分:0)
这是我使用的解决方案(部分由Alon Pini建议):
jQuery(function($) {
// Tab to next item when maxlength is reached
$(".postcode div:nth-child(1) input").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).parent().next().find('input').focus();
}
});
// Tab to previous item when pressing backspace and character count is 0
$("postcode div:nth-child(2) input").on('keyup', function(e) {
if(e.which==8) {
if (this.value.length == 0) {
$(this).parent().prev().find('input').focus();
}
}
});
});
此解决方案可以同时执行这两个操作,当字符数达到最大长度时,将重点放在下一个项目上,而当第二个输入字段中的字符数达到零时,将重点放在上一个项目上。