Skip to content

Instantly share code, notes, and snippets.

@keithshep
Last active August 29, 2015 14:03
Show Gist options
  • Save keithshep/e95ec70e28436a07465d to your computer and use it in GitHub Desktop.
Save keithshep/e95ec70e28436a07465d to your computer and use it in GitHub Desktop.
A little javascript class to help out with tri-state checkboxes.
/**
* A little "class" to help out with tri state checkboxes.
*/
function TriStateCheckbox(checkbox) {
var self = this;
var checkedVal = checkbox.prop("checked");
var indeterminatePropName = "indeterminate";
/**
* Set this to a function value that should be called when the state changes. This event
* will not be fired in response to programatic state changes (via the checked function)
*/
this.onTriStateChanged = null;
/**
* Get or set the checked state of this checkbox. The checked val can be true, false or
* null (which represents the indeterminate state)
* @param {boolean} [val]
* @return {boolean} iff this function is called with no val argument the current state is returned
*/
this.checked = function(val) {
if(typeof val === 'undefined') {
return checkedVal;
} else {
checkedVal = val;
oldCheckedVal = checkedVal;
if(val === null) {
checkbox.prop(indeterminatePropName, true);
checkbox.prop("checked", false);
} else {
checkbox.prop(indeterminatePropName, false);
checkbox.prop("checked", val);
}
}
};
var oldCheckedVal = checkedVal;
var changeFunc = function() {
checkbox.prop(indeterminatePropName, false);
checkedVal = checkbox.prop("checked");
// don't do anything if the value hasn't changed
if(checkedVal !== oldCheckedVal) {
oldCheckedVal = checkedVal;
// notify the listener
if(self.onTriStateChanged) {
self.onTriStateChanged();
}
}
};
checkbox.on("change", changeFunc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment