jquery - 检查输入字段的长度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2702862/
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
jquery - check length of input field?
提问by TwixxyKit
The code below is intended to enable the submit button once the user clicks in the textarea field. It works, but I'm trying to also make it so that it's only enabled if there's at least one character in the field. I tried wrapping it in:
下面的代码旨在在用户单击 textarea 字段后启用提交按钮。它有效,但我也试图使其仅在字段中至少有一个字符时才启用。我试着把它包装在:
if ($(this).val().length > 1)
{
}
But, that didn't seem to work... Any ideas?
但是,这似乎不起作用......有什么想法吗?
$("#fbss").focus(function () {
$(this).select();
if ($(this).val() == "Default text") {
$(this).val("");
$("input[id=fbss-submit]").removeClass();
$("input[id=fbss-submit]").attr('disabled', false);
$("input[id= fbss-submit]").attr('class', '.enableSubmit');
if ($('.charsRemaining')) {
$('.charsRemaining').remove();
$("textarea[id=fbss]").maxlength({
maxCharacters: 190,
status: true,
statusClass: 'charsRemaining',
statusText: 'characters left',
notificationClass: 'notification',
showAlert: false,
alertText: 'You have exceeded the maximum amount of characters',
slider: false
});
}
}
});
回答by Fyodor Soikin
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
这是行不通的,因为从其余的代码来看,文本输入的初始值是“默认文本”——多于一个字符,因此您的if
条件始终为真。
The simplest way to make it work, it seems to me, is to account for this case:
在我看来,使其工作的最简单方法是考虑这种情况:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
回答by user113716
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
如果您的意思是要在用户输入至少一个字符后启用提交,那么您需要附加一个键事件来为您检查。
Something like:
就像是:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});