Monday, 23 March 2009

Exclusive Checkbox jQuery Plug-in

Web interfaces like Hotmail often have a checkbox or radio button next to each item so that you can select that row. I've always disliked the radio button approach as you are limited to one row at a time eg when deleting. However sometimes you'd like to keep the checkboxes but have them behave like radio buttons. I couldn't find a really simple jQuery plug-in so I decided to write one. Original and minified versions at the end of the article. 

(Update: I changed the code slightly to use the official jQuery extend function for the plug-in definition, and to include the usage in the comments.)

* Exclusive Check Plugin v1.0.2
* Copyright (c) James Westgate
* @requires jQuery v1.3.2
* Dual licensed under the MIT and GPL licenses:
* @usage $('input:checked').exclusiveCheck();
* @usage $('form input:checked').exclusiveCheck();
* @usage $('table tbody input:checked').exclusiveCheck();

//Create closure
(function($) {

    //Plugin definition

        exclusiveCheck: function() {

            var selector = $(this);

            //Loop through each item in the matched set and apply event handlers
            return this.each(function(i) {

                //When the checkbox gets clicked, uncheck other checkboxes
                $(this).click(function(event) {

                    var clicked = this;

                    //Uncheck all except current
                    if (this.checked) {
                        selector.each(function() {
                            if (this != clicked) this.checked = false;

// end of closure

Download original and minified version.


Anonymous said...

Examples of use would be nice

Phillip Knezevich said...

There is a problem with the code: do not use $('input:checked')

you need to use: