(De)selecting All Checkboxes Using a Single Toggle - J Query

Problem
You need to select and deselect all checkboxes using a single toggle, in this case another checkbox. Additionally, that toggle should automatically switch states if some (or all)of the checkboxes are selected individually:

Solution

Target the toggle directly using its class attribute and the :checkbox selector. Then
cycle through each toggle found, determine the associated checkboxes using.siblings(), and attach the change event listeners:

Discussion

Using .eq(0).trigger('change') immediately executes the .change() event for the first checkbox. This sets the state of the toggle and protects against Firefox and other browsers that hold on to radio and checkbox states when the page is refreshed. The .eq(0) is used to only trigger the first checkbox’s change event. Without .eq(0),the .trigger('change') would be executed for every checkbox, but since they all share the same toggle, you only need to run it once.
What will happen when JavaScript is disabled? You should hide the toggle checkbox and label by default in CSS. Then use JavaScript to add a class name to a parent element that would override the previous CSS rule:


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics