I post comments via $ .ajax. However, I want to check that some content has been entered in the input field. At the moment I am using this:
if ($("#comments").val().length != 0){
However, this only works if the user leaves the input space, if you leave a space or return, then it will pass. How can I improve this if?
Delete the space before checking for empty:
if ($("#comments").val().replace(/^\s+|\s+$/g, "").length != 0){
you can go for the trim function ... google give us good links. btw ... jQuery has trim-function
trim
eg.
var trimmedValue = jQuery.trim($('#comments').val()); if (trimmedValue.length > 0) { // TODO }
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 using the Firebug console and the Chromium Developer Tools console).
I know this is an incredibly late answer, but I use this ...
var self = $(this).val(); if (!self || self[0] == ' '){ //////do something }
and it works well! hope someone else can benefit from it!