Thursday, February 25, 2010

Javascript code for selecting/de-selecting all Checkboxs

Check-boxes are useful for allowing the user to select multiple options when filling a HTML web form.

If the HTML Form is having large number of checkboxes, then selecting and de-selecting all the checkboxes will be difficult for the users. And, it will take significant amount of time.

So, we can provide separate button for allowing the users to select or de-select all the checkboxes by doing single click.

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

<form name="frmselectdeselectcheckbox" id="frmselectdeselectcheckbox" action="" method="post">

<input type="checkbox" name="selectdeselectcheckbox[]" id="selectdeselectcheckbox" value="1"/> <br>
<input type="checkbox" name="selectdeselectcheckbox[]" id="selectdeselectcheckbox" value="2"/><br>
<input type="checkbox" name="selectdeselectcheckbox[]" id="selectdeselectcheckbox" value="3" /> <br>

<input type="button" name="selectall" value="Select All" onClick="SetAllCheckBoxes('frmselectdeselectcheckbox','selectdeselectcheckbox',true);">
<input type="button" name="clearall" value="Clear All" onClick="SetAllCheckBoxes('frmselectdeselectcheckbox','selectdeselectcheckbox',false);">

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" type="text/javascript">
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
var objCheckBoxes = document.forms[FormName].elements[FieldName];
var countCheckBoxes = objCheckBoxes.length;
objCheckBoxes.checked = CheckValue;
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;


More Articles...

You can bookmark this blog for further reading, or you can subscribe to our blog feed.

No comments:

Search This Blog