Check All Checkboxes

How to Check All from a Single Checkbox in jQuery

Posted in Tutorials, jQuery Tutorials.
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading ... Loading ...
Share This:
DeliciousFacebookDiggRSS FeedStumbleUponTwitter

Suppose you want to check all listed checkboxes from a single checkbox. This is great for those who have scripts running a batch function. There are many different ways to implement this “check all checkboxes” functionality. I’m going to use an unordered list block in my code snippet.

This method of “check all checkboxes” UX/UI enhancement allows the end user to perform batch updates, modifcations, and deleting of unwanted content in a quick and user friendly way making tasks less repetitive. I’m sure you have seen many websites that do this and point being, it has become a standard in web 2.0 design.
The “Check All” Javascript Code Snippet

<script type="text/javascript">
$(document).ready(function(){
    $('#check_all').click(function(){
        var is_checked = $(this).attr('checked');
        $(this).closest('ul').find('input:checkbox').attr('checked', is_checked);
    });
});
</script>
<ul>
	<li><input id="check_all" type="checkbox" />Group 1</li>
	<li><input type="checkbox" />Child 1</li>
	<li><input type="checkbox" />Child 2</li>
	<li><input type="checkbox" />Child 3</li>
	<li><input type="checkbox" />Child 4</li>
</ul>

Demonstration

  • Group 1
  • Child 1
  • Child 2
  • Child 3
  • Child 4

Let’s evaluate exactly what is going on here. In the document ready, I assign a click event handler to the element id “check_all” which is my selector. When the check all element is checked, we assign a variable to the attribute value “checked” which returns boolean. The line after that, we do some traversing to the closest ul (since all the elements are within the unordered list). I then find all input types that are checkbox and alter the checked attribute accordingly by assigning the value from the “check all” element. It’s very straight forward. I hope you enjoy.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">