Created
March 16, 2015 17:49
-
-
Save mcaskill/136f4adde4b88695d759 to your computer and use it in GitHub Desktop.
Simple checkbox toggling with jQuery
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
/* global jQuery */ | |
/** | |
* Simple Checkbox Toggling | |
* | |
* Hands-free checked/unchecked toggling for all checkboxes. | |
* | |
* Requirements: | |
* - jQuery | |
* - `name="foo[]"` -- Name attribute must assign checked values to an array. | |
* | |
* Options (passed to `event.data`): | |
* - `all` -- The input value for the master toggler. | |
* | |
* Example: | |
* ```html | |
* <input type="checkbox" id="category-all" name="category[]" value="all"> | |
* <label for="category-all">Select All/None</label> | |
* ``` | |
* | |
* Features: | |
* - `data-checkbox-scoped` -- Add this data attribute to the parent | |
* of a collection of checkboxes to scope a set as a subset. | |
* | |
* Todo: | |
* - Exclude "all" from form submission. Probably just replace its | |
* value/name attributes with data attributes. | |
*/ | |
(function ($) { | |
'use strict'; | |
function CheckboxToggle ( event ) { | |
var $trigger, $checked, $checkboxes, $master, $scope; | |
all = ( event.data && event.data.all ? event.data.all : 'all' ); | |
$trigger = $( event.currentTarget ); | |
$scope = $trigger.parents('[data-checkbox-scoped]'); | |
$checkboxes = $( ':checkbox[name="' + $trigger.attr('name') + '"]', ( $scope.length ? $scope : null ) ).not(':disabled'); | |
if ( all === $trigger.val() ) { | |
$master = $trigger; | |
$checkboxes = $checkboxes.not( $master ); | |
$checkboxes.prop( 'checked', $master.prop('checked') ); | |
} | |
else { | |
$master = $checkboxes.filter('[value="' + all + '"]'); | |
$checkboxes = $checkboxes.not( $master ); | |
$checked = $checkboxes.filter(':checked'); | |
if ( $master.length ) { | |
$checkboxes = $checkboxes.not( $master ); | |
$master | |
.prop( 'checked', $checked.length > 0 ) | |
.prop( 'indeterminate', ( $checked.length > 0 && $checked.length < $checkboxes.length ) ); | |
} | |
} | |
}; | |
$(document).on( 'change.toggle-checkboxes', ':checkbox[name$="[]"]', CheckboxToggle ); | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment