MattsBits
MattsBits

MattsBits

Check, Uncheck And Toggle Checkboxes By Name  

by Matt Hawkins, 08/05/2009
Categories : JavaScript

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>


The function should be passed the name of your checkboxes and the mode you wish to operate in. For example to uncheck all the checkboxes with a name equal to myname you would use :

CheckBoxesByName('myname',0);


The function could be called from the onClick event. For example you could create the following text links :

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

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2022