Tag Archives: jquery

Using jQuery to give your user a “check all” option in the UI

Say you have a table where each row contains a check-box and you want to be able to check/uncheck every single check-box based on some action the user does. Using jQuery this is very easy. Assume we have the following HTML:

        <table>
            <thead>
                <tr>
                    <th><input type="checkbox" id="HeaderCheckbox"/></th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody>
                <tr><td><input type="checkbox"/></td><td>Tea</td></tr> 
                <tr><td><input type="checkbox"/></td><td>Coffee</td></tr> 
                <tr><td><input type="checkbox"/></td><td>Cola</td></tr> 
           </tbody>
        </table>

Then the following jQuery snippet will transform the HeaderCheckbox into a control that automatically checks or unchecks all the other check-boxes:

$(document).ready(function () {
    //Setup an eventhandler that fires 
    //when the user clicks on a control whose id = HeaderCheckbox
    $('#HeaderCheckbox').click(function (eventobject) {
       //the DOM element that triggered the event
       var $this = $(this);                       
       //Determine what the requested state is. 
       //I.e is the headercheck box checked or unchecked?
       var checked = $this.prop('checked');
       //Find each checkbox element below a <tr> and set 
       //it to the requested sate       
       $("tr :checkbox").prop('checked', checked) 
    })
})

If you’re using some framework with data-binding (e.g. Knockout) then its way better to simply bind each check box to a property of the the View Model and just set that property. The HTML would look like this

        <table >
            <thead>
                <tr>
                    <th><input type="checkbox" id="HeaderCheckbox" /></th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: Drinks">
                <tr>
                    <td><input type="checkbox" data-bind="checked: $data.Selected"/></td>
                    <td data-bind="text: $data.Name"></td>
                </tr>
            </tbody>
        </table>

And the associated JavaScript would look like this:

var DrinkViewModel = function () {
    this.Name           = ko.observable('');
    this.Selected       = ko.observable(false);
}

var viewModel = function () {
        var self = this
        //Holds all the drinks we want to list in the table
        this.Drinks = ko.observableArray();
}

$('#HeaderCheckbox').click(function (eventobject) {
    var $this = $(this);
    var checked = $this.prop('checked');
    $.each(MyViewModel.Drinks(), function (index, theDrink) 
    { 
        theDrink.Selected(checked) 
    })
})