Extend your own jQuery code

Posted on Wednesday July 13, 2011 / by Eric Potvin

Defining your own function can be very useful in any languages. jQuery it's a very rich JavaScript library that gives you the ability to add this functionality very easily. The goal will be to simply call any of your custom functions to be called like this:

$(element).function();

You will have to create the function using the "$.fn", which is a prototype of jQuery object. For example, you want to disable/enable input or select input in a form. Here's the definition:

$.fn.enable = function() { /* code */ };
$.fn.disable = function() { /* code */ };

In this case, the "code" inside the function will check if the element is a valid input or select.

if(this.is("input") || this.is("select")) {
/* code */
}

If so, based on the action (enable or disable), update the element:

// enable:
this.removeAttr("disabled");
//disable:
this.attr("disabled", true);

Here's the final result:

$.fn.disabled = function() {
    if(this.is("input") || this.is("select")) {
        this.attr("disabled", true);
    }
};

$.fn.enable = function() {
    if(this.is("input") || this.is("select")) {
        this.removeAttr("disabled");
    }
};

Now you simply need to call them:

$('input').enable();

to enable, or

$('input').disable();

to disable