035687df00d162cec025302373ebc076

I have a simple toggler to mass select (unselect) all input checkboxes with the "id" class in a form. It should be triggered from an anchor tag and have its text updated.

The things I don't like are the hard codings of the "mode" and the anchor text labels.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Q = jQuery.noConflict();

Q(document).ready(function(){
    Q("#toggler").click(function() {
        var mode = this.mode == 'off' ? 'on' : 'off';
        this.mode = mode;

        Q("form#the_form input.id").each(function(){
            mode == 'off' ? this.checked = true : this.checked = false;
        }); 

        Q(this).text() == 'check all' ? Q(this).text('uncheck all') : Q(this).text('check all');
        return false;
    });
};

// called from a link...
// <a href="#" id="toggler">check all</a>

Refactorings

No refactoring yet !

5071c5b861341c0dcfcf6ac86327701f

Tien Dung

October 6, 2008, October 06, 2008 22:19, permalink

1 rating. Login to rate!

Use true/false instead of using "on"/"off" for .mode
For .text() I think you can set it according to mode value

1
2
3
4
5
6
7
8
9
10
11
    Q("#toggler").click(function() {
        var mode = this.mode;
        this.mode = !mode;

        Q("form#the_form input.id").each(function(){
            this.checked = mode;
        }); 

        Q(this).text(mode ? 'check all' : 'uncheck all');
        return false;
    });
B9ab18362cacea38187b013657bb25fa

Leandro

October 16, 2009, October 16, 2009 15:11, permalink

No rating. Login to rate!

Thanks for sharing your code, but I am just fixing some a bug. This is the correct mode setting. Thanks.

1
2
3
4
5
6
7
8
9
10
11
    Q("#toggler").click(function() {
        var mode = this.mode ? false : true;
        this.mode = !mode;

        Q("form#the_form input.id").each(function(){
            this.checked = mode;
        }); 

        Q(this).text(!mode ? 'check all' : 'uncheck all');
        return false;
    });

Your refactoring





Format Copy from initial code

or Cancel