Saturday, March 15, 2008

javascript: How to select/deselect checkboxes

This function will select/deselect, tick/untick, check/uncheck all checkboxes belonging to a group. It can be used by a button to toggle a checkbox collection (e.g. Struts multibox in DisplayTag).


function toggle (checkboxes, isSelectAll)
{
if (checkboxes != null)
{
for (i = 0; i < checkboxes.length; i++)
{
checkboxes[i].checked = isSelectAll;
}
}
}


Usage: You can call this function on two buttons:
- select button: onclick="CheckboxUtil.toggle(document.formName.checkboxName, true)"
- deselect button: onclick="CheckboxUtil.toggle(document.formName.checkboxName, false)"


where:
- formName = name of the form.
- checkboxName = name of the checkbox group

Make sure all your checkboxes have the same checkboxName.

No comments: