Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

jquery - check length of input field?

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:

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

        }
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...