tags:

views:

126

answers:

3

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?

+1  A: 

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
}
Andreas Niedermair
Untested but I would think you could go further and do jQuery.trim($("#comments").val()).length since the trim returns a string anyway. Not that the extra variable is really going to hurt anything.
thismat
as i'm always a friend of introducing extra variables, to have some possibility to debug, i would leave it that way :)
Andreas Niedermair
Can't argue that. I'm just in the habit (good or bad) of avoiding extra variables if I won't be reusing them. I could see a good case of reusing this if you're going to validate the actual content though.
thismat
Andreas Niedermair
+2  A: 

Remove whitespace before checking for empty:

if ($("#comments").val().replace(/^\s+|\s+$/g, "").length != 0){
Dominic Rodger
@dominic would this be any more useful than just using a trim?
Chris
@Chris - no - I just didn't know about jQuery's trim function.
Dominic Rodger
+1  A: 

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).

Vikrant Chaudhary
I don't agree with you: http://jsfiddle.net/cn2YH/
jerone
@jerone Don't try with "!" operator. See updated answer.
Vikrant Chaudhary
Ok, aldo it's a very weird way to check a statement, I give you that it works: http://jsfiddle.net/cn2YH/2/
jerone