Dirty Bird Design
Dirty Bird Design

Reputation: 5543

Make function more re-usable

I need to run a function that makes checkboxes behave like radio buttons. I know, long story. Anyway, I want to make it more re-usable and not have to rewrite it for each group. I have it working like this:

$(function() {
    var $apples = $('input.apples');
    $apples.click(function() {
        $apples.removeAttr('checked');
        $(this).attr('checked', true);
    });
});

How can I make this more global so that if I have another group of checkboxes .bannanas it will work for them as well without having to rewrite it?

thx

Upvotes: 0

Views: 85

Answers (3)

user113716
user113716

Reputation: 322522

Make a plugin:

Example: http://jsfiddle.net/YbGtE/2/

(function($) {
    $.fn.makeRadios = function() {
        var $items = this;
        return this.click(function() {
            $items.removeAttr('checked');
            $(this).attr('checked', true);
        });
    };
})( jQuery );

$('input.apples').makeRadios();
$('input.bananas').makeRadios();

EDIT: As requested in the comment below, to uncheck a checkbox on a double click, do this:

Example: http://jsfiddle.net/YbGtE/3/

(function($) {
    $.fn.makeRadios = function() {
        var $items = this;
        return this.click(function() {
            $items.removeAttr('checked');
            $(this).attr('checked', true);
        }).dblclick(function() {
            $items.removeAttr('checked');
        });
    };
})( jQuery );

$('input.apples').makeRadios();
$('input.bananas').makeRadios();

Upvotes: 5

Hamish
Hamish

Reputation: 23346

If you assume that each group of checkboxes has the same class attribute you could automate it with:

$(function() {
    var checkboxes = $('input:checkbox.asRadio');
    checkboxes.click(function() {
        var myClass = $(this).attr('class');
        checkboxes.each(function() {
            if($(this).attr('class') == myClass) $(this).removeAttr('checked');
        });
        $(this).attr('checked', true);
    });
});

Where the checkboxes you want to behave as radio fields have the 'asRadio' class as well.

Upvotes: 0

JAAulde
JAAulde

Reputation: 19560

Use the selector:

'input:checkbox'

Or, if only certain checkboxes should be changed, add a class to the selector:

'input:checkbox.makeRadio'

And add that class to the checkboxes you want changed.

Upvotes: 1

Related Questions