Skip to content

Instantly share code, notes, and snippets.

@blackfalcon
Forked from nathansmith/check_all.js
Created January 23, 2013 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackfalcon/4602816 to your computer and use it in GitHub Desktop.
Save blackfalcon/4602816 to your computer and use it in GitHub Desktop.
/*
Use like this (or with <dl>, <ol>, <table>)...
<ul>
<li>
<input type="checkbox" class="check-all" />
</li>
<li>
<input type="checkbox" />
</li>
<li>
<input type="checkbox" />
</li>
</ul>
*/
// Module pattern
var check_all = (function($, window, document, undefined) {
// Kickoff
$(document).ready(function() {
check_all.init();
});
// Expose publicly
return {
// check_all.init
init: function() {
// Run on DOM load, and click
function determine_checked(el) {
var parent = el.closest('dl, ol, table, ul');
var master = parent.find('input[type="checkbox"].check-all');
// Exit, if no "check-all" exists
if (!master.length) {
return;
}
var others = parent.find('input[type="checkbox"]').not('.check-all');
var others_checked = parent.find('input[type="checkbox"]:checked').not('.check-all');
// Is this the master checkbox?
if (el.hasClass('check-all')) {
// Is it checked?
if (el.is(':checked')) {
// Check all
others.prop('checked', true);
}
else {
// Un-check all
others.prop('checked', false);
}
}
// Must be a sibling checkbox
else {
// Are all siblings checked?
if (others.length === others_checked.length) {
// Check master
master.prop('checked', true);
}
else {
// Un-check master
master.prop('checked', false);
}
}
}
$(document.documentElement).off('click.check_all').on('click.check_all', 'input[type="checkbox"]', function() {
var el = $(this);
determine_checked(el);
});
$('input[type="checkbox"].check-all').each(function() {
var el = $(this);
determine_checked(el);
});
}
};
})(jQuery, this, this.document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment