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.



Qualitypoint.blogspot.com

Qualitypointtech.com

Qualitypointtech.net







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"/> Qualitypoint.blogspot.com <br>
<input type="checkbox" name="selectdeselectcheckbox[]" id="selectdeselectcheckbox" value="2"/> Qualitypointtech.com<br>
<input type="checkbox" name="selectdeselectcheckbox[]" id="selectdeselectcheckbox" value="3" /> Qualitypointtech.net <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);">
</form>


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)
{
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>


More Articles...


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

No comments:

Search This Blog