-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcbFamily.js
50 lines (47 loc) · 1.89 KB
/
cbFamily.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Make a checkbox parent of other checkboxes. Functionality:
* - If the parent is clicked the children are checked/unchecked based on the parent.
* - If all the children are checked, parent gets checked too.
* - If there is an unchecked item in the children and if the parent is checked, it gets unchecked.
* - children can be a function. In this case, that function is run agaist the parent in order to find the children.
* This is useful for groups of checkboxes.
* - Checks/unchecks parent based on the initial status of its children at start.
*
* Example group usage:
* $(".titles input:checkbox").cbFamily(function (){
* return $(this).parents("div:first").next().find("input:checkbox");
* });
*
* Based and improved on http://tech.tiffanyandjeremy.com/Articles/Two-level-JQuery-check-and-uncheck-all-child-checkboxes-of-a-parent-checkbox
*/
;(function ($) {
$.fn.cbFamily = function (children) {
return this.each(function () {
var $this = $(this);
var els;
if ($.isFunction(children)) {
els = children.call($this);
} else {
els = $(children);
}
$this.bind("click.cbFamily", function () {
els.prop('checked', this.checked).change();
});
function checkParent() {
$this.prop('checked',
els.length == els.filter("input:checked").length);
}
els.bind("click.cbFamily", function () {
if ($this.prop('checked') && !this.checked) {
$this.prop('checked', false).change();
}
if (this.checked) {
checkParent();
$this.change();
}
});
// Check parents if required on initialization
checkParent();
});
};
})(jQuery);