Check all checkboxes in HTML table using jQuery
HTML Markup
To get started, create a standard HTML table on the page. For this demo, our table has 4 columns: checkbox in the first column, then Name, Age, and Country, along with some random data. The checkbox is present in the table header as well as in every table row. When the header checkbox is checked, all the checkboxes in the table rows are also checked and vice versa. Here, only the header row checkbox has an ID attribute.
Name | Age | Country | |
---|---|---|---|
Maria Anders | 30 | Germany | |
Francisco Chang | 24 | Mexico | |
Roland Mendel | 100 | Austria | |
Helen Bennett | 28 | UK | |
Yoshi Tannamuri | 35 | Canada | |
Giovanni Rovelli | 46 | Italy | |
Alex Smith | 59 | USA |
CSS
The following CSS classes are used to style the table and its rows. There are also styles defined to provide alternate colors to the table rows.
jQuery Code
To implement this functionality, we need to attach a click event to the header checkbox and all the table row checkboxes as well. The solution also takes care of updating the header checkbox status based on the status of the table row checkboxes.
The following is the outline of the jQuery solution:
- First, attach a click event to the header checkbox. In the event, based on its status, check/uncheck HTML table row checkboxes.
- Attach a click event handler to all HTML table row checkboxes. In the event, check the clicked checkbox status and header checkbox status. We’ll also need to update the header row checkbox status based on table row checkbox status. If the clicked checkbox status is false and the header checkbox status is true, then uncheck the header checkbox. When the clicked checkbox status is checked, loop through all the other checkboxes to find out if all are checked or not. If all are checked, then also check the header checkbox.
Here is the complete jQuery code:
You can see the demo here!
Conclusion
To sum it up, we’ve just learned how to implement check/uncheck checkbox functionality to select HTML table rows based on the header row checkbox status. This solution also updates the header checkbox status based on the status of all the table row’s checkboxes. Based on your needs, you can easily modify this section to take further action on the cell value.