Javascript 当输入文本字段达到最大长度时移动焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1959398/
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
Moving a focus when the input text field reaches a max length
提问by TK.
I do have a credit card number form. The number is divided into four parts just as on a real credit card.
我有信用卡号表格。就像真实的信用卡一样,这个数字被分成四个部分。
I want to add a JavaScript taste to the form where when a user types four letters in a field, the focus automatically goes to the next tag. But not in the last tag. By doing this, a user doesn't have to type "tab" key to move a focus.
我想为表单添加 JavaScript 风格,当用户在字段中键入四个字母时,焦点会自动转到下一个标签。但不是在最后一个标签中。通过这样做,用户不必键入“tab”键来移动焦点。
It is okay to add some extra class, id or name in the tags.
可以在标签中添加一些额外的类、ID 或名称。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>MoveFocus</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
// some code goes here.
});
</script>
</head>
<body>
<form action="post.php" method="post" accept-charset="utf-8">
<input type="text" value="" id="first" size="4" maxlength="4"/> -
<input type="text" value="" id="second" size="4" maxlength="4"/> -
<input type="text" value="" id="third" size="4" maxlength="4"/> -
<input type="text" value="" id="fourth" size="4" maxlength="4"/>
<p><input type="submit" value="Send Credit Card"></p>
</form>
</body>
</html>
回答by Tauren
I haven't used this tool before, but it does what you want. You could just look at it's source to get some ideas:
我以前没有使用过这个工具,但它可以满足您的需求。你可以看看它的来源以获得一些想法:
For your situation, you would add this code:
对于您的情况,您可以添加以下代码:
<script type="text/javascript" src="jquery.autotab.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#first').autotab({ target: '#second', format: 'numeric' });
$('#second').autotab({ target: '#third', format: 'numeric', previous: '#first' });
$('#third').autotab({ previous: '#second', format: 'numeric' });
});
</script>
回答by Michael Zuschlag
As others have urged, don't do this. Users are not going to be able to anticipate that you'll auto-tab them, and this will drive them nuts. Have you thought about users who copy and paste their credit card? What is the benefit of using four fields anyway?
正如其他人所敦促的那样,不要这样做。用户将无法预料到您会自动标记他们,这会让他们发疯。您是否考虑过复制粘贴信用卡的用户?无论如何,使用四个字段有什么好处?
Also, not all credit cards divide their numbers into four sets of four. American Express divides them into three groups of numbers, for example. Dynamically adding and removing text fields is asking for trouble in this case.
此外,并非所有信用卡都将其数字分成四组,每组四组。例如,美国运通将它们分成三组数字。在这种情况下,动态添加和删除文本字段会带来麻烦。
Instead, use your Javascript to automatically insert the spaceswhere they belong, advancing the cursor, not the focus. The first digit in the number indicates the type of credit card (5 is Mastercard, 4 is Visa, 3 is American Express…), so you can read this to decide where to add the spaces. Scrub the spaces out of the string when you post it. This approach will save you and your users a lot of pain.
相反,使用您的 Javascript 自动插入它们所属的空格,推进光标,而不是焦点。数字中的第一个数字表示信用卡的类型(5 是万事达卡,4 是 Visa,3 是美国运通卡……),因此您可以阅读此内容来决定在何处添加空格。发布时擦去字符串中的空格。这种方法将为您和您的用户节省很多痛苦。
回答by Ouadie
As @Sander suggested, the easy way to do an auto-tab is:
正如@Sander 所建议的,执行自动选项卡的简单方法是:
jQuery("form input[type=text]").on('input',function () {
if(jQuery(this).val().length == jQuery(this).attr('maxlength')) {
jQuery(this).next("input").focus();
}
});
Updateby @morespace54
由@morespace54更新
oninputis an html5event is supported on IE9+, so you can use keyupinstead.
oninput是IE9+支持的html5事件,因此您可以改用。keyup
回答by Doguhan Uluca
I highly recommend using the Masked Input jQuery Plugin.
我强烈推荐使用Masked Input jQuery Plugin。
Your usage will look like this:
您的用法如下所示:
$("#CreditCardNumber").mask("9999-9999-9999-9999");
This way you'll have copy-paste and placeholder support.
通过这种方式,您将获得复制粘贴和占位符支持。
回答by Marcelo Lazaroni
If your form fields are one beside the other like in your example, you could simply take advantage of nextElementSiblingand voilà!
如果您的表单字段与您的示例中的一样,您可以简单地利用nextElementSibling和瞧!
function skipIfMax(element) {
max = parseInt(element.dataset.max)
if (element.value.length >= max && element.nextElementSibling) {
element.nextElementSibling.focus();
}
}
<input type="text" data-max=2 oninput="skipIfMax(this)"/>
<input type="text" data-max=3 oninput="skipIfMax(this)"/>
<input type="text" data-max=4 oninput="skipIfMax(this)"/>
<input type="text" data-max=5 oninput="skipIfMax(this)"/>
回答by Roland Bouman
A very simple solution could go like this:
一个非常简单的解决方案可能是这样的:
<script type="text/javascript">
function input_onchange(me){
if (me.value.length != me.maxlength){
return;
}
var i;
var elements = me.form.elements;
for (i=0, numElements=elements.length; i<numElements; i++) {
if (elements[i]==me){
break;
}
}
elements[i+1].focus();
}
</script>
<form action="post.php" method="post" accept-charset="utf-8">
<input type="text" value="" id="first" size="4" maxlength="4"
onchange="input_onchange(this)"
/> -
<input type="text" value="" id="second" size="4" maxlength="4"
onchange="input_onchange(this)"
/> -
<input type="text" value="" id="third" size="4" maxlength="4"
onchange="input_onchange(this)"
/> -
<input type="text" value="" id="fourth" size="4" maxlength="4"
onchange="input_onchange(this)"
/> -
<p><input type="submit" value="Send Credit Card"></p>
</form>
回答by Sander Rijken
I haven't tested it, but I think this will work. It will probably also move the focus to the button when the 4th field is completed.
我还没有测试过,但我认为这会奏效。当第四个字段完成时,它可能还会将焦点移到按钮上。
$("form input").change(function () {
var maxLength = $(this).attr('maxlength');
if($(this).val().length == maxLength) {
$(this).next().focus();
}
}
回答by Sander Rijken
This does not have four fields, but it does validate credit cards (integrity check, not Luhn's Algorithm!). I have to tell you how annoying it is to use multiple fieldsfor a user and auto-tabbing. I recommend you only use one field.
这没有四个字段,但它确实验证信用卡(完整性检查,而不是 Luhn 算法!)。我必须告诉你为用户使用多个字段和自动标签是多么烦人。我建议您只使用一个字段。
From jquery website:
$("#myform").validate({
rules: {
field: {
required: true,
creditcard: true
}
}
});
/
/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: {
required: true,
creditcard: true
}
}
});
});
</script>
<style>#field { margin-left: .5em; float: left; }
#field, label { float: left; font-family: Arial, Helvetica, sans-serif; font-size: small; }
br { clear: both; }
input { border: 1px solid black; margin-bottom: .5em; }
input.error { border: 1px solid red; }
label.error {
background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/unchecked.gif') no-repeat;
padding-left: 16px;
margin-left: .3em;
}
label.valid {
background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
display: block;
width: 16px;
height: 16px;
}
</style>
</head>
<body>
<form id="myform">
<label for="field">Required, creditcard (try 446-667-651): </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
</html>

![Javascript Angularjs:错误:[ng:areq] 参数“HomeController”不是函数,未定义](/res/img/loading.gif)