HowTo: check all checkboxes in a table to select/deselect all rows with jQuery
Mi first tech post is about a recent trick that I wrote in JavaScript to let the user be able to check all the checkbooks in a table, the standard problem that everyone has bumped on in a website that has use interaction with lot of datas.
First of all we have to write the structure of our HTML table, here is a sample:
1 2 3 4 5 6 7 8 9 10 |
<table class="table table-condensed table-hover table-striped"> <tbody> <tr> <th scope="col"></th> </tr> <tr> <td><span class="checkbox checkbox-row_selection" title="Select Row"><input id="chk_sel_row" name="chk_sel_row" type="checkbox" /></span></td> </tr> </tbody> </table> |
The page render follows:
With a very little function in JavaScript, with the help of jQuery, we can cycle through the table rows and check all the checkbooks that are wrapped into a span with the classes “checkbox checkbox-row_selection”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//The Function to Select/Deselect all the rows in the table that has chackbox with the structure: span.checkbox.checkbox-row_selection > input type=checkbox //$p_tbody : jQuery object with the table's TBODY //p_action : select / deselect function GLOBAL_checkAll_checkbox_row_selection($p_tbody, p_action) { if (p_action == null || (p_action != "select" && p_action != "deselect")) p_action = "select"; $p_tbody.children('tr').each(function (e) { var _$check = $(this).children('td:first-child').children('span.checkbox.checkbox-row_selection').children('input[type=checkbox]'); if (_$check != null) { if (p_action == "deselect" || (_$check.is(':checked') && p_action == "select")) { p_action = "deselect"; _$check.prop('checked', false); } else { _$check.prop('checked', true); } } }); }; |
In the document ready section of our JavaScript we have to associate the onClick event on a button or anything we want the user to click to select or deselect our checkbox, here is the code:
1 2 3 4 5 6 7 8 9 |
$(document).ready(function () { //Check All for tables that have an element with the custom class "allRows-selector" $('table tbody tr > th > .allRows-selector').click(function (e) { var action = "select"; GLOBAL_checkAll_checkbox_row_selection($(this).parent('th').parent('tr').parent('tbody'), action); }) }); |