Javascript 输入某个字符时,使用 jQuery 将光标移动到另一个字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5198061/
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
use jQuery to move the cursor to another field when a certain character is typed?
提问by Vivian River
I have two text fields in my web page. The user is supposed to enter two numbers seperated by a hyphen ("-") character. The numbers may be between 1 and 10 digits each. I need the cursor to move to the next field when the user presses the hyphen key.
我的网页中有两个文本字段。用户应该输入由连字符(“-”)字符分隔的两个数字。每个数字可能在 1 到 10 位之间。当用户按下连字符键时,我需要光标移动到下一个字段。
I can easily move the cursor using $('#txtField2').focus()
. However, I still have the problem that the hyphen character remains in the first text field. How can I easily supress the hyphen from appearing in the first text field?
我可以使用 轻松移动光标$('#txtField2').focus()
。但是,我仍然遇到连字符保留在第一个文本字段中的问题。如何轻松抑制连字符出现在第一个文本字段中?
回答by nyuszika7h
回答by David says reinstate Monica
Assuming a simplified html of:
假设一个简化的 html:
<form action="#" method="post">
<fieldset>
<label for="numOne">Number:</label>
<input type="text" id="numOne" name="numOne" />
<input type="text" id="numTwo" name="numTwo" />
</fieldset>
</form>
The following should work, or serve as an example:
以下应该工作,或作为一个例子:
$('#numOne').keypress(
function(e){
if (e.which == 45) {
$(this).next('input:text').focus();
return false; // prevents the '-' being entered.
}
});
Incidentally, I used $(this).next('input:text')
rather than an id-based selector to allow for more general application and re-use.
顺便说一句,我使用$(this).next('input:text')
而不是基于 id 的选择器来允许更通用的应用程序和重用。
References:
参考:
回答by Martin Jespersen
I'd do it like this:
我会这样做:
$('#input1').keypress(function(e) {
if(e.keyCode == 45) {
e.preventDefault();
$('#input2').focus();
}
});
see live example here: http://jsfiddle.net/wjNP3/2/
在这里查看现场示例:http: //jsfiddle.net/wjNP3/2/
回答by HymanJoe
you could "listen" to that character and just focus the other field and prevent it from inputing
你可以“听”那个字符,只关注另一个字段并阻止它输入
回答by Jauhardev
Maybe this can help you:
也许这可以帮助你:
HTML
HTML
<div>
<p>Insert Your Number:</p>
<input type="number" value="" id="first" >
<input type="number" value="" id="second" >
<input type="number" value="" id="third" >
<input type="submit" id="submit">
</div>
jQuery
jQuery
$("#first").on("keypress", function(){
if($("#first").val().length == 4){
$("#second").focus();
}
})
$("#second").on("keypress", function(){
if($("#second").val().length == 4){
$("#third").focus();
}
})
$("#third").on("keypress", function(){
if($("#third").val().length == 5){
$("#submit").focus();
}
})
OR you can check Live DEMO by CLICK HERE!