Archive

Archive for December, 2010

Three State HTML Checkboxes

December 5, 2010 2 comments

I wanted a 3 state checkbox, using jQuery. Here’s how I did it.

$('input[type="checkbox"]').each(function () {
    // keep a reference to the current checkbox
    var me = $(this);
    // define the three states our checkbox can enter:
    // checked, not checked, and faded out
    var states = [
        function () {
            me.val(true);
            me.attr('checked', 'checked');
            me.css({ opacity: 1 });
        },
        function () {
            me.val(false);
            me.removeAttr('checked');
            me.css({ opacity: 1 });
        },
        function () {
            me.val('null');
            me.removeAttr('checked');
            me.css({ opacity: 0.5 });
        }
    ];
    // start off in the not checked state
    var currentState = 1;
    // whenever the checkbox is changed, loop through our checkbox states
    me.change(function () {
        states[++currentState > 2 ? currentState = 0 : currentState]();
    });
    // force it into the next state:
    // I want it to start off in the faded out state (currentState == 2)
    me.change();
});

Works for me. Whether or not breaking HTML conventions is a good thing… that’s up to you.

Categories: JavaScript, JQuery
Follow

Get every new post delivered to your Inbox.