jQuery control grouping

I recently had a requirement to enable disable a whole bunch of controls based on a checkbox value. The first thing I did was to give each group of controls a css class name which they all share.

HTML

    <input type="checkbox" value="Master Checkbox" id="group1" />
    <input type="checkbox" value="Some option" class="group1" />
    <input type="checkbox" value="Some value" class="group1" />

Next came a little bit of jQuery to set up the groups. This code does the initial enabling/disabling of the group of controls as appropriate and also wires up the click handler for when the user changes the master checkbox value

$.fn.enable = function (value) {
    return this.each(function () {
        if (typeof this.disabled != "undefined") this.disabled = !value;
    });
}

function ConfigureGroup(groupName) {
    EnableGroup(groupName);
    $('#' + groupName).bind('click', function () {
        EnableGroup(groupName);
    });
}

function EnableGroup(groupName) {
    var flag = $('#' + groupName).attr('checked');
    $('.' + groupName).enable(flag);
}

Then in my page startup code I just make calls to ConfigureGroup

function PageStartup() {
    ConfigureGroup('group1');
}

$(document).ready(function () {
    PageStartup();
});

Not the most amazing piece of code ever written, but I was pleased with it as it cut down the javascript in the existing page quite considerably.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s