Tuesday, May 18, 2010

Checkbox select all jQuery plugin for a table

/*
 * File: jquery.checkboxselection.js
 *
 * Plugin to create checkbox in the table
 * It needs table has correct structure (at least with head and body) and
 * there are checkboxs in row's first cell both in header in body
 */

(function($) {
    $.fn.checkboxSelection = function() {
        return this.each(function() {
            var table = this;
            var headCheckbox = $('thead th:first :checkbox', table).click(function() {
                $('tbody tr', table).find('td:first :checkbox').attr('checked', this.checked);
            })
            var checkSelection = function() {
                var trs = $('tbody tr', table).find('td:first');
                headCheckbox.attr('checked', trs.find('input:checked').length == trs.find(':checkbox').length);
            }
            $('tbody tr', this).find('td:first :checkbox').click(checkSelection);
            checkSelection();
        });
    }
})(jQuery);
HTML:
<table>
    <thead>
        <tr>
            <th><input type="checkbox"></th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" name="a[1]"></td>
            <td>John Smith</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="a[2]"></td>
            <td>Jack Daniels</td>
        </tr>
    </tbody>
</table>
Using:
$('table').checkboxSelection();