JSFiddle - React, Tailwind, and code Playground
by mqchen
HTML
<input type="checkbox" data-checkboxgroup-master="a b" data-checkboxgroup-master-checkedwhen="any" />
<input type="checkbox" data-checkboxgroup="a" />
<input type="checkbox" data-checkboxgroup="a" />
<br />
<input type="checkbox" data-checkboxgroup-master="b" data-checkboxgroup="a" data-checkboxgroup-master-checkedwhen="all" />
<input type="checkbox" data-checkboxgroup="b a" />
<input type="checkbox" data-checkboxgroup="b" />
JavaScript
var checkboxGroup = function(customParent, customOpt) {
this.parent = customParent || $("body");
this.options = {
eventNS : ".checkboxgroup",
memberAttr : "data-checkboxgroup",
masterAttr : "data-checkboxgroup-master",
masterCheckedWhenAttr : "data-checkboxgroup-master-checkedwhen"
};
$.extend(this.options, customOpt, true);
this._addEvents();
};
checkboxGroup.prototype._processMemberUpdate = function(groupId) {
var groupChx = $("[" + this.options.memberAttr + "~='" + groupId + "']", this.parent);
var masterChx = $("[" + this.options.masterAttr + "~='" + groupId + "']", this.parent);
var checkedCount = groupChx.filter(":checked").length;
var uncheckedCount = groupChx.filter(":not(:checked)").length;
// update master
masterChx.prop("indeterminate", checkedCount > 0 && uncheckedCount > 0);
// Check or uncheck master
$.each(masterChx, function(index, master) {
master = $(master);
var when = master.attr(this.options.masterCheckedWhenAttr) || "any";
master.prop("checked",
(when == "all" && uncheckedCount === 0)
|| (when === "any" && checkedCount > 0)).trigger("change" + this.options.eventNS);
}.bind(this));
};
checkboxGroup.prototype._processMasterUpdate = function(groupId) {
$("[" + this.options.masterAttr + "~=" + groupId + "]", this.parent).each(function(index, master) {
var master = $(master);
var groupChx = $("[" + this.options.memberAttr + "~='" + groupId + "']", this.parent);
master.prop("indeterminate", false);
groupChx.prop("checked", master.is(":checked"));
}.bind(this));
};
checkboxGroup.prototype._addEvents = function() {
$("[" + this.options.memberAttr + "]", this.parent).on("change" +...