使用 Javascript 自动将光标移动到下一个表单字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15337084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Javascript to Auto move cursor onto next form field
提问by Apb
Is it possible using Javascipt
to automatically send the user from one field to the next when the maxlength
of the field has been reached?
是否可以在到达字段Javascipt
时自动将用户从一个字段发送到下一个字段maxlength
?
If so, how?
如果是这样,如何?
采纳答案by Gaurav Agrawal
yes it is possible. Suppose your textbox max length is 5. You need to make an function onkeyup event and count the length of the textbox value. In this function if length is equal or exceed to 5 then you need to write second textbox focus function calls.
对的,这是可能的。假设您的文本框最大长度为 5。您需要创建一个函数 onkeyup 事件并计算文本框值的长度。在此函数中,如果长度等于或超过 5,则您需要编写第二个文本框焦点函数调用。
回答by Grant Thomas
回答by Sudip Pal
Yes, you need to calculate the number of charecter inserted in the field by onkeyup
event and if the number is equal to maxlength then set the focus
to next field
是的,您需要通过onkeyup
事件计算在字段中插入的字符数,如果数量等于 maxlength,则将其设置focus
为下一个字段
回答by jcubic
you can use code like this using jquery. In this code it will move to #second field when text is larger then 20 characters
您可以使用 jquery 使用这样的代码。在此代码中,当文本大于 20 个字符时,它将移动到 #second 字段
<input id="first"/>
<input id="second"/>
<script>
$(function() {
$('#first').keypress(function() {
var self = $(this);
//wait until character is inserted
setTimeout(function() {
if (self.val().length > 20) {
$('#second').focus();
}
}, 1);
});
});
</script>
回答by PSR
$('#productkey1').keyup(function() {
if(this.value.length >= $(this).attr('maxlength'))
{
$('#productkey2').next().focus();
}
});
回答by Dave Anderson
First you need to hook into the onfocus
event for the input to know you are starting the measuring. Then you need to check the length of the entered characters with the onkeyup
event. Once your limit is reached you can call focus()
on the next DOM element you want to move the cursor to. You will also need to use the onblur
event to know that you have stopped measuring the length of an input.
首先,您需要挂钩输入的onfocus
事件以了解您正在开始测量。然后你需要用onkeyup
事件检查输入的字符的长度。达到限制后,您可以调用focus()
要将光标移动到的下一个 DOM 元素。您还需要使用该onblur
事件来知道您已停止测量输入的长度。
For example, using jQuery;
例如,使用jQuery;
<input id="inputA" type="text"/>
<input id="inputB" type="text"/>
<script>
var $input;
$('#inputA').focus(function() {
$input = $(this);
});
$(window).keyup(function() {
if($input && $input.val().length == 5) {
$('#inputB').focus();
}
});
$('#inputA').blur(function() {
$input = null;
});
</script>