简体   繁体   English

jquery - 检查输入字段的长度?

[英]jquery - check length of input field?

The code below is intended to enable the submit button once the user clicks in the textarea field.下面的代码旨在在用户单击 textarea 字段后启用提交按钮。 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:我试着把它包装在:

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
            });

        }
    }
});

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" ) ...

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
    }
});

alternatively using keyup()或者使用 keyup()

 $("#fbss").keyup(function() {
 if($(this).val().length >1) {
    $('#submit').prop('disabled', false);
   }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM