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
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…
coooolllllllllllllllll