RSS Amplifier

LakTEK · Jan 7, 2011

jQuery isBlank()

0
Sign in to vote or save

This page did not load. You can still read it on the original site — the toolbar below keeps your place in the directory.

One of my favorite syntactic sugar methods available in Rails is the Object.blank? , which evaluates to true if the given object is false, empty, or a whitespace string. It makes your conditional expressions more readable; avoiding the use of boolean operators. It would be cool if we can have the same convenience when writing client-side code with JavaScript. Unfortunately, jQuery Core doesn't…

One of my favorite syntactic sugar methods available in Rails is the Object.blank?, which evaluates to true if the given object is false, empty, or a whitespace string. It makes your conditional expressions more readable; avoiding the use of boolean operators.

It would be cool if we can have the same convenience when writing client-side code with JavaScript. Unfortunately, jQuery Core doesn't have such a utility function. Closest you get is with the jQuery.isEmptyObject. It would return true for null, undefined or empty objects and empty arrays; but you can't match whitespace strings with it (which are of course not empty objects).

So, I wrote this small jQuery plugin to check whether the given object is blank:

(function($){
  $.isBlank = function(obj){
    return(!obj || $.trim(obj) === "");
  };
})(jQuery);
$.isBlank(" ") //true
$.isBlank("") //true
$.isBlank("\n") //true
$.isBlank("a") //false
$.isBlank(null) //true
$.isBlank(undefined) //true
$.isBlank(false) //true
$.isBlank([]) //true

As shown in the above examples, it would identify any object that evaluates to false (null, undefined, false, []) or a whitespace string as blank.

Update: jtarchie commented on this gist suggesting a alternative method, which would even match the empty objects.

Read on laktek.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.