So after answering a question about nested linked checkboxes I mentioned it at work and surprisingly it turned out to be similar to something we needed.
The requirements were:
- a "Select all" checkbox
- a nested "Select all" checkbox (only selects a small portion)
- Cannot rely upon the hierarchy of the markup. The given fiddle is an example only. EDIT:- from Discussions with John I now see there was this requirement and so I've added it.
So realising it was different to the aforementioned question I set about writing my own. I aimed for readability and minimal markup.
(function($) {
$('input[type=checkbox][data-children]').unbind("change childchange childchangebubble").each(function() {
var parent = $(this);
var linkedChildren = $(parent.data("children"));
//trigger a "childChange" event on the parent when any child is triggered.
linkedChildren.bind("change childchangebubble", function() {
parent.trigger("childchange");
});
parent.bind({
"change": function(event) { // Bind change event to check all children
linkedChildren.prop("checked", parent.prop("checked")).trigger("change");
},
"childchange": function() { // have to bind custom event seperately, there seems to be a jQuery bug.
// When a child is changed recalculate if parent should be checked
var noChildrenUnchecked = !linkedChildren.is(":not(:checked)");
parent.prop("checked", noChildrenUnchecked).trigger("childchangebubble");
}
});
});
})(jQuery);
the data-children attributes that are rendered to the page look like: data-children="#child2sub1, #child2sub2" on the parent and nothing extra needed on the children.
I'd love any feedback on readability/maintainability, performance etc.
current jsFiddle.