Javascript code for selecting/de-selecting all Checkboxs

Check boxes in web pages allow the users to select multiple options while they fill out a HTML form.

If the HTML form consists of large number of checkboxes , then individually selecting and de-selecting all the checkboxes will be a pain staking job. This might irritate some users and hence we should place an option/button to select and deselect all these checkboxes on a whole.

Inorder to solve this issue using javascript you can add code to select and deselect all the checkboxes by doing a single click.

For providing above form, the HTML code will be as below

A javascript function “SetAllCheckBoxes” will be called in the onClick event of the Select All and Clear All buttons.

This javascript function should be added in the head section of the HTML file.

<script language=”javascript”>
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}

</script>

Posted in General Tagged with: , ,