开发者

prevent empty submissions in <textarea>

I have set up a <textarea> and functions that will pick up keystrokes. I have it set up where if the user presses Enter, the text typed in the text area will be submitted to a database.

However, I want to prevent from submitting empty text, just pressing Enter and submitting. I also noticed that when Enter, a new line is created, so I can't just check if the text is "" or if its length is 0 because the second time around there will be a new line.

The jQuery for detecting using the keyboard is:

$(document).ready(function(){
    $('.active-buddy-tab div#chat-window form#chat-message textarea#message').live('keydown', function(event) {

        var key = event.which;

        // all keys including return
        if (key >= 33) {

            var maxLength = $(this).attr("m开发者_运维问答axlength");
            var length = this.value.length;

            if (length >= maxLength) {
                event.preventDefault();
            }
        }
    });

    $('.active-buddy-tab div#chat-window form#chat-message textarea#message').live('keyup', function(e) {

        if (e.keyCode == 13) {

            var text = $(this).val();
            var maxLength = $(this).attr("maxlength");
            var length = text.length;

            var to = $('.active-buddy-tab div h3 p#to').text();

            if (length <= maxLength + 1) {
                chat.send(text, from, to);
                chat.update(from, to);
                $(this).val("");
            } else {
                $(this).val(text.substring(0, maxLength));
            }

        }
    });
});

So how can I prevent from sending an empty message? I apologize if this is really simple, maybe I'm thinking too hard about this.

Thanks, Hristo


if( $.trim( $(this).val() ) == "" ) // empty

trim

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜