views:

46

answers:

1

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("maxlength");
            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

+5  A: 
if( $.trim( $(this).val() ) == "" ) // empty

trim

Dan Heberden
Thanks. That worked. What exactly does the `$.trim()` do?
Hristo
removes whitespace from the beginning and end of the string
Dan Heberden
oh ok... fair enough. Thanks :)
Hristo
Well at first i thought it didn't catch newlines but it does :) glad to help
Dan Heberden