Reputation: 1936
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
Reputation: 25495
... or if you are interested in using some of the latest HTML5 options:
use form validation for the various input fields (eg email, url, req'd: http://bit.ly/Z8ZEHe
use modernizr to check if the visitor's browser supports HTML5 forms, and if it doesn't load a fallback polyfill:
http://modernizr.com
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
Good luck!
Upvotes: 0
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
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