Home > JavaScript, JQuery > Three State HTML Checkboxes

Three State HTML Checkboxes

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
  1. December 5, 2010 at 10:45 pm | #1

    Hah, don’t judge me for liking my own blog post. Wasn’t sure what that “Like” button did, because it didn’t look like a Facebook Like button… turns out it’s a WordPress thing. Boring…

  2. sukirti
    March 14, 2012 at 8:38 am | #2

    coooolllllllllllllllll

  1. No trackbacks yet.

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.