jQuery Utilities

These are useful utilities that were forgotten by JavaScript and jQuery.

Method
$.isDefined( oValue )
Determine if the value is defined (i.e. not undefined).
$.isUndefined( oValue )
Determine if the value is undefined.
$.isNothing( oValue )
Determine if the value is undefined or null.
$.isObject( oValue )
Determine if the value is an object and not null.
$.isString( oValue )
Determine if the value is a string.
$.isBlank( oValue )
Determine if the value is null or an empty string.
$.asString( oValue, sDefault )
Convert object to a string or return default value if cannot convert.
$.asInt( oValue, sDefault )
Convert object to an integer or return default if cannot convert.
$.asFloat( oValue, sDefault )
Convert object to a float or return default if cannot convert.
$.asBool( oValue, sDefault )
Convert object to a boolean or return default if cannot convert.
$.applyPluginSingleton( jqObject, oPlugin, args )
Apply operation on a singleton handler to a JQuery object.
$.applyPluginHandler( jqObject, sName, fnCreator, args )
Create or apply handlers to DOM objects in the list of elements in a JQuery object.

function $.isDefined(oValue)

Determine if the value is defined (i.e. not undefined).

Arguments:
oValue
Object to determine if defined.
(return)
If type of "oValue" is "undefined" then return false else return true.

This method is useful to determine if a property or method of an object is defined. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.isDefined()                    // false
   $.isDefined(undefined)           // false
   $.isDefined(null)                // true
   $.isDefined([])                  // true
   $.isDefined({})                  // true
   $.isDefined(oTest)               // true
   $.isDefined(oTest.xxx)           // false
   $.isDefined(oTest.something)     // true
   $.isDefined(oTest.aArray)        // true
   $.isDefined(oTest.aObject)       // true
   $.isDefined(oTest.afunction)     // true
      

function $.isUndefined(oValue)

Determine if the value is undefined.

Arguments:
oValue
Object to determine if undefined.
(return)
If type of "oValue" is "undefined" then return true else return false.

This method is useful to determine if a property or method of an object is undefined. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.isUndefined()                    // true
   $.isUndefined(undefined)           // true
   $.isUndefined(null)                // false
   $.isUndefined([])                  // false
   $.isUndefined({})                  // false
   $.isUndefined(oTest)               // false
   $.isUndefined(oTest.xxx)           // true
   $.isUndefined(oTest.something)     // false
   $.isUndefined(oTest.aArray)        // false
   $.isUndefined(oTest.aObject)       // false
   $.isUndefined(oTest.afunction)     // false
      

function $.isNothing(oValue)

Determine if the value is undefined or null.

Arguments:
oValue
Object to determine if undefined or null.
(return)
If type of "oValue" is "undefined" or the value of "oValue" is null then return true else return false.

This method is useful to determine if a property or method of an object is undefined or set to null. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.isNothing()                    // true
   $.isNothing(undefined)           // true
   $.isNothing(null)                // true
   $.isNothing([])                  // false
   $.isNothing({})                  // false
   $.isNothing(oTest)               // false
   $.isNothing(oTest.xxx)           // true
   $.isNothing(oTest.something)     // false
   $.isNothing(oTest.aArray)        // false
   $.isNothing(oTest.aObject)       // false
   $.isNothing(oTest.afunction)     // false
      

function $.isObject(oValue)

Determine if the value is an object and not null.

Arguments:
oValue
Object to determine if an object and not null.
(return)
If type of "oValue" is "object" and the value of "oValue" is not null then return true else return false.

This method is useful to determine if a property or method of an object is a valid object. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.isObject()                     // false
   $.isObject(undefined)            // false
   $.isObject(null)                 // false
   $.isObject([])                   // false
   $.isObject({})                   // true
   $.isObject(oTest)                // true
   $.isObject(oTest.xxx)            // false
   $.isObject(oTest.something)      // true
   $.isObject(oTest.aArray)         // false
   $.isObject(oTest.aObject)        // true
   $.isObject(oTest.afunction)      // false
      

function $.isString(oValue)

Determine if the value is a string.

Arguments:
oValue
Object to determine if a string.
(return)
If type of "oValue" is "string" then return true else return false.

This method is useful to determine if a property is a string. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.isString()                     // false
   $.isString(undefined)            // false
   $.isString(null)                 // false
   $.isString([])                   // false
   $.isString({})                   // false
   $.isString("")                   // true
   $.isString(oTest)                // false
   $.isString(oTest.xxx)            // false
   $.isString(oTest.something)      // true
   $.isString(oTest.aArray)         // false
   $.isString(oTest.aObject)        // false
   $.isString(oTest.afunction)      // false
      

function $.isBlank(oValue, bTrim)

Determine if a value is undefined, null or a blank string.

Arguments:
oValue
Value to check.
bTrim
Default=true. Indicates blank space is trimmed if the value is a string.
(return)
The following pseudo logic is performed:
  • If "oValue" is undefined or null then return true.
  • If "oValue" is not a string return false.
  • If "oValue" is a string and has zero length return true.
  • If "oValue" is a string, "bTrim" is true and resulting trimmed string has zero length return true.
  • Otherwise return false.

The need for this method is more common than expected, many times I find a need to determine if a string value is undefined, null or just blank. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.isBlank()                      // true
   $.isBlank(undefined)             // true
   $.isBlank(null)                  // true
   $.isBlank([])                    // false
   $.isBlank({})                    // false
   $.isBlank("")                    // true
   $.isBlank("   ")                 // true
   $.isBlank(null, true)            // true
   $.isBlank([], true)              // false
   $.isBlank({}, true)              // false
   $.isBlank("", true)              // true
   $.isBlank("   ", true)           // true
   $.isBlank(null, false)           // true
   $.isBlank([], false)             // false
   $.isBlank({}, false)             // false
   $.isBlank("", false)             // true
   $.isBlank("   ", false)          // false
   $.isBlank(oTest)                 // false
   $.isBlank(oTest.xxx)             // true
   $.isBlank(oTest.something)       // false
   $.isBlank(oTest.aArray)          // false
   $.isBlank(oTest.aObject)         // false
   $.isBlank(oTest.afunction)       // false
      

function $.asString(oValue, sDefault)

Convert object to a string or return default if cannot convert.

Arguments:
oValue
Value to be converted to a string.
sDefault
Default value if value is undefined, nothing or cannot be converted to a string.
(return)
Value as string or default value.

This method is useful to convert anything to a string or provide a useful default value. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { }
               , quoteTest: "a \"test\" for quote's" } ;
   $.asString()                        // undefined
   $.asString(undefined)               // undefined
   $.asString(null)                    // undefined
   $.asString(undefined, null)         // null
   $.asString(null, undefined)         // undefined
   $.asString(null, null)              // null
   $.asString(null, "xxx")             // "xxx"
   $.asString(-.1, "xxx")              // "-0.1"
   $.asString(0, "xxx")                // "0"
   $.asString(true, "xxx")             // "true"
   $.asString(false, "xxx")            // "false"
   $.asString(oTest.xxx, "xxx")        // "xxx"
   $.asString(oTest.quoteTest, "xxx")  // "a \"test\" for quote's"
      

function $.asInt(oValue, iDefault)

Convert object to an integer or return default if cannot convert.

Arguments:
oValue
Value to be converted to an integer.
iDefault
Default value if value is undefined, nothing or cannot be converted to an integer.
(return)
Value as integer or default value.

This method is useful to convert anything to an integer or provide a useful default value. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.asInt()                        // undefined
   $.asInt(undefined)               // undefined
   $.asInt(null)                    // undefined
   $.asInt(undefined, null)         // null
   $.asInt(null, undefined)         // undefined
   $.asInt(null, null)              // null
   $.asInt(null, 99)                // 99
   $.asInt([], 99)                  // 99
   $.asInt({}, 99)                  // 99
   $.asInt("", 99)                  // 99
   $.asInt("xxx", 99)               // 99
   $.asInt(0)                       // 0
   $.asInt(0, 99)                   // 0
   $.asInt(42, 99)                  // 42
   $.asInt(-42, 99)                 // -42

   $.asInt("0", 99)                 // 0
   $.asInt("-.1", 99)               // 0
   $.asInt("42", 99)                // 42
   $.asInt("-42", 99)               // -42

   $.asInt("0x", 99)                // 0
   $.asInt("-.1x", 99)              // 0
   $.asInt("42x", 99)               // 42
   $.asInt("-42x", 99)              // -42

   $.asInt("x0", 99)                // 99
   $.asInt("x-.1", 99)              // 99
   $.asInt("x42", 99)               // 99
   $.asInt("x-42", 99)              // 99

   $.asInt(oTest.xxx, 99)           // 99
   $.asInt(oTest.aArray, 99)        // 99
   $.asInt(oTest.aObject, 99)       // 99
      

function $.asFloat(oValue, fDefault)

Convert object to a float or return default if cannot convert.

Arguments:
oValue
Value to be converted to a float.
fDefault
Default value if value is undefined, nothing or cannot be converted to a float.
(return)
Value as float or default value.

This method is useful to convert anything to a float or provide a useful default value. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.asFloat()                        // undefined
   $.asFloat(undefined)               // undefined
   $.asFloat(null)                    // undefined
   $.asFloat(undefined, null)         // null
   $.asFloat(null, undefined)         // undefined
   $.asFloat(null, null)              // null
   $.asFloat(null, 99)                // 99
   $.asFloat([], 99)                  // 99
   $.asFloat({}, 99)                  // 99
   $.asFloat("", 99)                  // 99
   $.asFloat("xxx", 99)               // 99
   $.asFloat(0)                       // 0
   $.asFloat(0, 99)                   // 0
   $.asFloat(-.1, 99)                 // -0.1
   $.asFloat(42, 99)                  // 42
   $.asFloat(-42, 99)                 // -42

   $.asFloat("0", 99)                 // 0
   $.asFloat("-.1", 99)               // -0.1
   $.asFloat("42", 99)                // 42
   $.asFloat("-42", 99)               // -42

   $.asFloat("0x", 99)                // 0
   $.asFloat("-.1x", 99)              // -0.1
   $.asFloat("42x", 99)               // 42
   $.asFloat("-42x", 99)              // -42

   $.asFloat("x0", 99)                // 99
   $.asFloat("x-.1", 99)              // 99
   $.asFloat("x42", 99)               // 99
   $.asFloat("x-42", 99)              // 99

   $.asFloat(oTest.xxx, 99)           // 99
   $.asFloat(oTest.aArray, 99)        // 99
   $.asFloat(oTest.aObject, 99)       // 99
      

function $.asBool(oValue, bDefault)

Convert object to a boolean or return default if cannot convert.

Arguments:
oValue
Value to be converted to a boolean.
bDefault
Default value if value is undefined, nothing or cannot be converted to a boolean.
(return)
Value as boolean or default value.

This method is useful to convert anything to an boolean or provide a useful default value. Special check is made for strings that begin with "Y"/"N", "T"/"F" or a numeric value. Sample return value with various inputs are shown below.

   var oTest = { something: "xxx", aArray: [ 1, 2 ]
               , aObject: { a: 1 }, afunction: function () { } } ;
   $.asBool()                        // default false
   $.asBool(undefined)               // default false
   $.asBool(null)                    // default false
   $.asBool(undefined, true)         // default true
   $.asBool(null, true)              // default true
   $.asBool([], true)                // default true
   $.asBool({}, true)                // default true

   $.asBool("", true)                // default true
   $.asBool("xxx", true)             // default true

   $.asBool("Yes", true)             // true, string begins with "y".
   $.asBool("yes", true)             // true, string begins with "y".
   $.asBool("No", true)              // false, string begins with "n".
   $.asBool("no", true)              // false, string begins with "n".

   $.asBool("true", true)            // true, string begins with "t".
   $.asBool("false", true)           // false, string begins with "f".

   $.asBool(0)                       // false
   $.asBool(0, true)                 // false
   $.asBool(42, true)                // true
   $.asBool(-42, true)               // true

   $.asBool("0", true)               // false, integer value is zero
   $.asBool("-.1", true)             // false, integer value is zero
   $.asBool("42", true)              // true, integer value is not zero
   $.asBool("-42", true)             // true, integer value is not zero

   $.asBool("0x", true)              // false, integer value is zero
   $.asBool("-.1x", true)            // false, integer value is zero
   $.asBool("42x", true)             // true, integer value is not zero
   $.asBool("-42x", true)            // true, integer value is not zero

   $.asBool("x0", true)              // default true
   $.asBool("x-.1", true)            // default true
   $.asBool("x42", true)             // default true
   $.asBool("x-42", true)            // default true

   $.asBool(oTest.xxx, true)         // default true
   $.asBool(oTest.aArray, true)      // default true
   $.asBool(oTest.aObject, true)     // default true
      

function $.applyPluginSingleton(jqObject, oPlugin, args)

Apply operation on a singleton handler to a JQuery object.

Arguments:
jqObject
jQuery object to apply plugin to, normally is "this".
oPlugin
Plugin singleton object to apply.
args
Arguments to the method. If first argument is a string, it is assumed to be the name of the method to invoke.
(return)
Value provided by method.

This method provides a generic implementation of "Plugin Methods" defined in the JQuery authoring documentation at the URL http://docs.jquery.com/Plugins/Authoring#Plugin_Methods

A singleton handler is a single object that contains a list of methods that can be invoked on a jQuery object. The method invoked is determined from the first argument if it is a string; otherwise the method "init" is invoked.

If "args[0]" is a string, then it is used to obtain the method to invoke within the handler (i.e. "oPlugin[args[0]]".) Otherwise method "init" is invoked.

The arguments passed to the method invoked is the "jqObject" followed by the arguments in "args" excluding "args[0]" if it is a string.

The following is an example of how this method is used for the "tooltip" example.

   var methods = {
      init: function( options ) {
      },
      show: function() {
      },
      hide: function() {
      },
      update: function( content ) {
      }
   };

   $.fn.tooltip = function(sCommand) {
      return $.applyPluginSingleton(this, methods, arguments);
   }

   // calls the init method
   $('div').tooltip(); 

   // calls the init method
   $('div').tooltip({
     foo : 'bar'
   });

   // calls the hide method
   $('div').tooltip('hide'); 

   // calls the update method
   $('div').tooltip('update', 'This is the new tooltip content!'); 
      

function $.applyPluginHandler(jqObject, sName, fnCreator, args)

Create or apply handlers to DOM objects in the list of elements in a JQuery object.

Arguments:
jqObject
jQuery list of elements, normally is "this".
sName
Name of key of data object for storing handler object in element.
fnCreator
Constructor function for the plugin handler objects. This function should have the form “function myHandler(oElement, ….)”, where “this” is the handler object being constructed, “oElement” is the element the handler object is being constructed for and any additional arguments passed by the caller.
args
Arguments to constructor and commands. If first argument is a string, it is assumed to be the name of the method to invoke.
(return)
Value of "jqObject".

This method provides a generic implementation of "Plugin Methods" defined in the JQuery authoring documentation at the URL http://docs.jquery.com/Plugins/Authoring#Plugin_Methods

A plugin handler is an object that is created for each element being handled. This method will create the handler using the "fnCreator" function if the handler does not exist, otherwise it will use the exiting handler.

If "args[0]" is a string, then it is used to obtain the method to invoke within the handler (i.e. "oHandler[args[0]]".) Otherwise no method is invoked.

The arguments passed to the constructor and method invoked is a "oElement" followed by the arguments in "args" excluding "args[0]" if it is a string. The object "this" is set to the plugin handler object.

If the handler object has a string property called "name" it will be used to report errors for the object, otherwise the name of the constructor is used.

The following is an example of how this method is used for the "emptyTextInput" plugin.

function emptyTextInput(oElement, oOptions) {
   /// <summary>
   /// Element handler for managing empty message of a text input field.
   /// </summary>
   /// <param name="oOptions" type="object">Control options.</param>
   /// <returns></returns>
   /// <remarks></remarks>
   var self = this;
   self.name = "emptyTextInput";
   console.log("emptyTextInput: %s", oElement.name);

   //---------------------------------------------------------------------
   // Define status.
   self.status = {
      // Options to this extension.
      EmptyText: 'search keyword',  // Text when input field is empty.
      EmptyClass: null,             // Class to add when field is empty.

      // Status information.
      jqElement: $(oElement),       // Original JQuery element.
      hasFocus: false,              // Indicates field has focus.
      hasEmptyText: false           // Indicates field is empty.
   };
   $.extend(self.status, oOptions);

   var jqElement = self.status.jqElement;

   try {
      var sOptions = jqElement.attr(self.name);
      if (!$.isBlank(sOptions)) 
         $.extend(self.status, $.JSONparse(sOptions));
   } catch (err) {
      // Ignore errors.
   }

   //---------------------------------------------------------------------
   // Perform edits on status.
   if ($.isBlank(self.status.EmptyClass)) 
      self.status.EmptyClass = null;

   var sValue = jqElement.val();
   if ($.isBlank(sValue) || (sValue == self.status.EmptyText)) {
      jqElement.val(self.status.EmptyText);
      self.status.hasEmptyText = true;
      if (self.status.EmptyClass) 
         jqElement.addClass(self.status.EmptyClass);
   } else {
      self.status.hasEmptyText = false;
      if (self.status.EmptyClass) 
         jqElement.removeClass(self.status.EmptyClass);
   }

   //---------------------------------------------------------------------
   // Define event handlers.
   self._onfocus = function () {
      console.log("emptyTextInput._onfocus: %s", this.name);
      if (self.status.hasEmptyText
            && (this.value == self.status.EmptyText)) {
         this.value = "";
         self.status.hasEmptyText = false;
      }
      if (self.status.EmptyClass) 
         $(this).removeClass(self.status.EmptyClass);
      self.status.hasFocus = true;
      return true;
   }
   jqElement.bind("focus", self._onfocus);

   self._onblur = function () {
      console.log("emptyTextInput._onblur: %s", this.name);
      if (this.value == "") {
         this.value = self.status.EmptyText;
         self.status.hasEmptyText = true;
         if (self.status.EmptyClass) 
            $(this).addClass(self.status.EmptyClass);
      }
      self.status.hasFocus = false;
      return true;
   }
   jqElement.bind("blur", self._onblur);

   return self;
}
$.fn.emptyTextInput = function (oOptions) {
   /// <summary>
   /// Manages empty message for a text input field.
   /// </summary>
   /// <param name="oOptions" type="object">Control options.</param>
   /// <returns></returns>
   /// <remarks></remarks>
   return $.applyPluginHandler(this.filter("input:text"), 
                               "emptyTextInput", 
                               emptyTextInput, 
                               arguments);
}