Sometimes you want to check, uncheck or toggle a number of checkboxes using either buttons or text links.
If your text boxes have a name attribute the function below can be used to either select all, select none or toggle the existing setting.
Here is a JavaScript function which can be placed in the head tags of your html page :
<script language="JavaScript">
<!-- Begin
function CheckBoxesByName(sName,sMode)
{
// This function checks/unchecks or toggles all
// text boxes with their name attribute set to sName
//
// mode 0 - Uncheck
// mode 1 - Check
// mode 2 - Toggle
//
// http://www.mattsbits.co.uk
var boxes = document.getElementsByName(sName);
var i=0;
// For each checkbox with name sName
for (i=0;i<=boxes.length;i++)
{
// Make sure we are dealing with checkboxes
if (boxes[i].type=="checkbox") {
switch (sMode) {
case 0:
// Uncheck checkbox
boxes[i].checked = false;
break;
case 1:
// Check checkbox
boxes[i].checked = true;
break;
case 2:
// Toggle checkbox
if (boxes[i].checked == true) {
boxes[i].checked = false;
} else {
boxes[i].checked = true;
}
break;
}
}
}
}
// End -->
</script>
CheckBoxesByName('myname',0);
<a href="#" onClick="CheckBoxesByName('myname',0); return false;">Check None</a>
<a href="#" onClick="CheckBoxesByName('myname',1); return false;">Check All</a>
<a href="#" onClick="CheckBoxesByName('myname',2); return false;">Check Toggle</a>