Skip to content

Instantly share code, notes, and snippets.

@skowron-line
Last active January 2, 2016 08:28
Show Gist options
  • Save skowron-line/8276211 to your computer and use it in GitHub Desktop.
Save skowron-line/8276211 to your computer and use it in GitHub Desktop.
check parent elements, uncheck child
$.fn.checkUncheck = function(options){
var defaults = {
onCheck: jQuery.noop,
onUnCheck: jQuery.noop
};
settings = $.extend({}, defaults, options);
$(this).each(function(){
var e = $(this);
e.click(function(){
if(e[0].checked) {
checkParent(e.data('parent'));
settings.onCheck.call(e);
} else {
uncheckChild(e.val());
settings.onUnCheck.call(e);
}
})
})
var checkParent = function(parentId) {
var p = $('input[type=checkbox][value='+parentId+']');
if(0 === p.length) {
return;
}
checkParent(p.data('parent'));
p[0].checked = true;
settings.onCheck.call(p);
},
uncheckChild = function(parentId) {
var c = $('input[type=checkbox][data-parent='+parentId+']:checked');
if(0 === c.length) {
return;
}
c.each(function(){
var e = $(this);
uncheckChild(e.val());
e[0].checked = false;
settings.onUnCheck.call(e);
})
}
}
//Usage
$(document).ready(function(){
$('input[type=checkbox][data-parent]').checkUncheck({
onCheck: function() {
console.log($(this));
}
});
})
//Example
http://jsfiddle.net/skowron_line/kepWL/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment