Easiest “check all” ever with jQuery
Posted August 6, 2009 by Brian Cray
Reading time: About 1 minute
How does it work?
This code checks/unchecks all checkboxes within the same fieldset. Simple and semantic.
Example completed code
See this in action and view the source if you’d like.
HTML Setup
Add checkboxes however you like, just make sure they are within the same fieldset.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <fieldset> // these will be affected by check all <div><input type="checkbox" class="checkall"> Check all</div> <div><input type="checkbox"> Checkbox</div> <div><input type="checkbox"> Checkbox</div> <div><input type="checkbox"> Checkbox</div> </fieldset> <fieldset> // these won't be affected by check all; different fieldset <div><input type="checkbox"> Checkbox</div> <div><input type="checkbox"> Checkbox</div> <div><input type="checkbox"> Checkbox</div> </fieldset> |
The “check all” jQuery
I must say this is genius… and fast! I spent a lot of time tweaking this code for performance and brevity. Enjoy!!
Updated: Thanks to comments from k3n and Nate I was able to streamline the original code even more! K3n’s code in particular was genius*2.
1 2 3 4 5 | $(function () { // this line makes sure this code runs on page load $('.checkall').click(function () { $(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked); }); }); |
6 Article references from other blogs
1009
24 Article comments
Show/add comments