Jquery: 强制光标优雅地进入下一个输入字段?
Jquery: force cursor into next input field gracefully?
我有 4 个相邻的输入字段。
我试图强制用户在每个输入字段中输入 1 个字符,一旦他们输入 1 个字符,他们就需要在下一个字段中输入下一个字符,直到输入完成。
但是我目前的代码到处都是,我不知道我需要做什么才能实现这个。
这是我的代码:
https://jsfiddle.net/ej9tvosj/
$('.inps').keydown(function (event) {
// check for hyphen
var myLength = $(this).val().length;
if(myLength ==0){
$(this).next('.inps').focus();
}
});
如果您在第一个字段中输入内容,它会跳到下一个字段,但之后会变得混乱。
有人可以就此问题提出建议吗?
您可以将 myLength
值与 1
进行比较,如下面的代码片段所示:
$('.inps').keydown(function (event) {
// check for hyphen
var myLength = $(this).val().length;
if(myLength ==1){
$(this).next('.inps').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
您需要尝试 on input
侦听器而不是 keyup
来检测输入的变化,因为您需要确保在更改焦点之前输入了一个字符。
$(document).on('input', '.inps', function (event) {
// check for hyphen
var myLength = $(this).val().trim().length;
if(myLength ==1){
$(this).next('.inps').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
我有 4 个相邻的输入字段。
我试图强制用户在每个输入字段中输入 1 个字符,一旦他们输入 1 个字符,他们就需要在下一个字段中输入下一个字符,直到输入完成。
但是我目前的代码到处都是,我不知道我需要做什么才能实现这个。
这是我的代码:
https://jsfiddle.net/ej9tvosj/
$('.inps').keydown(function (event) {
// check for hyphen
var myLength = $(this).val().length;
if(myLength ==0){
$(this).next('.inps').focus();
}
});
如果您在第一个字段中输入内容,它会跳到下一个字段,但之后会变得混乱。
有人可以就此问题提出建议吗?
您可以将 myLength
值与 1
进行比较,如下面的代码片段所示:
$('.inps').keydown(function (event) {
// check for hyphen
var myLength = $(this).val().length;
if(myLength ==1){
$(this).next('.inps').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
您需要尝试 on input
侦听器而不是 keyup
来检测输入的变化,因为您需要确保在更改焦点之前输入了一个字符。
$(document).on('input', '.inps', function (event) {
// check for hyphen
var myLength = $(this).val().trim().length;
if(myLength ==1){
$(this).next('.inps').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >