Thursday, June 24, 2010

JavaScript: Checkbox - Select All

A very common scenario in a HTML table with check-box(s), a select / un-select all. Here is a simple approach to do that using JavaScript viz.,
1. Let's have two links (like gmail) to Select All and UnSelect All.
2. Let the two functions call a single function to do the operation. The function will accept the following parameters viz.,

    1. A boolean value where true => Select / false => UnSelect
    2. The name mentioned for the checkbox.

function fnCheckAll(status)
    var arrCheckBoxList;
    var iCounter;
    arrCheckBoxList = document.getElementsByTagName('checkboxlist');

        arrCheckBoxList[iCounter].checked = status;

The following is a HTML snippet to call the function viz.,

<a href=”javascript:void(0);” onclick=”javascript:fnCheckAll(true);”>Select All</a>

<a href=”javascript:void(0);” onclick=”javascript:fnCheckAll(false);”>UnSelect All</a>

Note: All the checkboxes should have the same name passed in the second parameter.

This JavaScript snippet will do the trick. :)


Please leave your comments here...