silvster27
silvster27

Reputation: 1936

How to tell if user entered text into a textarea using jquery

I am doing some form validation, and I have a textarea that has an initial placeholder in it, and I'm trying to check if the user has entered any data into the textarea.

If I check using jquery .text() it doesn't see the text being added at the browser level, and if I use .val() nothing is updated there in the first place. So what's the proper way to do this check prior to submitting the form?

<div>
   <textarea class="myUserText"></textarea>
</div>

function validateForm(){
   if($('.myUserText').text()==""){
        //do something here
   }
}

Upvotes: 1

Views: 835

Answers (3)

David Taiaroa
David Taiaroa

Reputation: 25495

... or if you are interested in using some of the latest HTML5 options:

Good luck!

Upvotes: 0

Blender
Blender

Reputation: 298106

.val() should work. Catch the submit event as well:

$('form').submit(function(e) {
    if (!$('.myUserText').val() == '') {
        e.preventDefault();
        // The form won't submit
    }
});

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074028

and if I use .val() nothing is updated there in the first place. So what's the proper way to do this check prior to submitting the form?

val is the correct thing to check, and will be != "" if the user has entered something in the textarea.

Of course, the thing they've entered could be just a newline, which may not be what you want. So you might consider:

if($('.myUserText').val().replace(/^\s+/, "") === "")

...which ignores leading whitespace.

Upvotes: 1

Related Questions