Last active
October 24, 2017 12:01
-
-
Save henrik/71378 to your computer and use it in GitHub Desktop.
jQuery checkbox utilities: check range, master toggle box, check/uncheck all.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// jQuery checkbox utility plugin. | |
// Triggers "change" events on the checkboxes. | |
// By Henrik Nyh <http://henrik.nyh.se> 2009-04-27 under the MIT License. | |
(function($) { | |
function makeChecked($checkboxes, checked) { | |
return $checkboxes.prop("checked", checked).trigger("change"); | |
} | |
// Check a range of boxes by clicking one, then another while holding Shift or Command. | |
// Code from http://www.barneyb.com/barneyblog/projects/jquery-checkbox-range-selection/ | |
// modified to support Command and so it can be reapplied after JS re-sort without issues. | |
// $('#container :checkbox').enableCheckboxRangeSelection(); | |
$.fn.enableCheckboxRangeSelection = function() { | |
var lastCheckbox = null; | |
var $spec = this; | |
$spec.unbind("click.checkboxrange"); | |
$spec.bind("click.checkboxrange", function(e) { | |
if (lastCheckbox != null && (e.shiftKey || e.metaKey)) { | |
var $checkboxes = $spec.slice( | |
Math.min($spec.index(lastCheckbox), $spec.index(e.target)), | |
Math.max($spec.index(lastCheckbox), $spec.index(e.target)) + 1 | |
) | |
makeChecked($checkboxes, e.target.checked); | |
} | |
lastCheckbox = e.target; | |
}); | |
return $spec; | |
}; | |
// $(':checkbox').checkAll(); | |
$.fn.checkAll = function() { | |
return makeChecked($(this), true); | |
}; | |
// $(':checkbox').uncheckAll(); | |
$.fn.uncheckAll = function() { | |
return makeChecked($(this), false); | |
} | |
// Master checkbox that can check/uncheck other checkboxes: | |
// $('#slaves :checkbox').checkAllWith('#master:checkbox'); | |
jQuery.fn.checkAllWith = function(master) { | |
$slaves = $(this); | |
$master = $(master); | |
// If the control box is initially checked, check the others, but not the other way around. | |
if ($master.prop('checked')) { | |
makeChecked($slaves, true); | |
} | |
(function($master, $slaves) { // Closure to allow multiple checkAllWith in one page | |
$master.click(function() { | |
makeChecked($slaves, !!$master.prop('checked')); | |
}); | |
})($master, $slaves); | |
return $slaves; | |
}; | |
})(jQuery); |
Changed attr -> prop in the Gist for compatibility with jQuery 1.9+.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! I have the shift-selection feature done into a jQuery plugin, but I'm using the
$.fn.prop
instead of$.fn.attr
. Take a look at it and if you feel like contributing you are welcome: http://rmariuzzo.github.io/checkboxes.js/