如何使用 jQuery 提交并检查值是否为 2 - 5 个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15656622/
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
How to use jQuery to onsubmit and check if the value is 2 - 5 characters?
提问by Dora
Let's say I have a text field:
假设我有一个文本字段:
Username: <input type="text" id="username" class="required" />
<input type="submit" />
and I have some jQuery:
我有一些 jQuery:
$(document).ready(function() {
user = $("#username");
user.submit(function() {
})
})
I want to check if the length of the value entered in username
is between 2 - 5 characters after I submit. If it's not then something happens.
我想在提交后检查输入的值的长度username
是否在 2 - 5 个字符之间。如果不是,那么就会发生一些事情。
I'm not too sure what I should be inside the user.submit(function(){})
.
我不太确定我应该在user.submit(function(){})
.
回答by adeneo
First you'll need an actual form:
首先你需要一个实际的表格:
<form id="myForm">
Username: <input type="text" id="username" class="required" />
<input type="submit" />
</form>
then:
然后:
$(document).ready(function(){
$('#myForm').on('submit', function(e){
e.preventDefault();
var len = $('#username').val().length;
if (len < 6 && len > 1) {
this.submit();
}
});
});
Or in HTML5 you can use the pattern
attribute (not supported in Safari and IE9-and below):
或者在 HTML5 中,您可以使用该pattern
属性(Safari 和 IE9 及以下不支持):
<form id="myForm">
Username: <input type="text" id="username" pattern=".{2,5}" required />
<input type="submit" />
</form>
回答by Piet van Dongen
You can check the value of the input field with user.val()
and the length of the string with user.val().length
.
您可以使用 来检查输入字段的值user.val()
和字符串的长度user.val().length
。
That way you can do something like this:
这样你就可以做这样的事情:
if(user.val().length < 2 || user.val().length > 5) {
console.log('test')
}
回答by Johan Hoeksma
I made a Fiddle
我做了一个小提琴
You can use a statement as
您可以将语句用作
$(document).ready(function(){
$("#form").submit(function(e) {
length = $("#username").val().length;
if((length > 2 && length < 5)) {
$("#output").html("correct, logging in");
} else {
$("#output").html("incorrect, must have 3 or 4 chars");
}
return (length > 2 && length < 5);
});
});
And HTML
和 HTML
<form id="form" method="POST" action="http://www.cnn.com">
username: <input type="text" id="username" class="required" />
<input type="submit" />
回答by Adil
Bind submit to form
instead of input type textand check its value in submit event. It would be better to assign some id to form and use form id selector to bind submit.
将提交绑定到form
而不是输入类型文本并在提交事件中检查其值。最好为表单分配一些 id 并使用表单 id 选择器来绑定提交。
$('form').submit(function(){
username = $('#username').val();
if(username.length > 1 && username.length < 6)
{
}
});