Reputation: 6665
I'm submitting some comments via $.ajax. However I want to check to make sure that some content is entered in the input box. At the moment I am using this:
if ($("#comments").val().length != 0){
However this only works if a user leaves in the input blank, if the leave a space or return then it will pass. How can I improve this if?
Upvotes: 14
Views: 18402
Reputation: 1977
I know this is an incredibly late answer, but I am using this...
var self = $(this).val();
if (!self || self[0] == ' '){
//////do something
}
and it works well! hope someone else can get some use out of it!
Upvotes: 1
Reputation: 11319
In JavaScript
//Following all return true
"" == false
" " == false
" " == false
" " == false
//Not related to question but interesting
//Following all (also) return true
!" " == false
!" " == false
!" " == false
//Except
!"" == false //returns false
(Verified with Firebug console and Chromium's Developer Tools console).
Upvotes: 2
Reputation: 99841
Remove whitespace before checking for empty:
if ($("#comments").val().replace(/^\s+|\s+$/g, "").length != 0){
Upvotes: 22
Reputation:
you might go for a trim
-function ... google give us some nice links.
btw ... jQuery does have a trim-function
eg.
var trimmedValue = jQuery.trim($('#comments').val());
if (trimmedValue.length > 0) {
// TODO
}
Upvotes: 19