PDA

View Full Version : Select/unselect all checkbox fields using pure Javascript and HTML



m3andros
02-20-2008, 12:09 AM
The following code allows you to select multiple fields without having to select each checkbox one by one. This code is especially useful if you're developing a form or a CMS that allows you to delete and/or modify several items with one click. Enjoy:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Select All </title>

<meta http-equiv="Content-type" value="text/html; charset=UTF-8" />

<script type="text/javascript" language="javascript">
function SetAllCheckBoxes(FormName, AreaID, CheckValue)
{
if(!document.forms[FormName])
return;
var objCheckBoxes = document.getElementById(AreaID).getElementsByTagName('input');
if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = CheckValue;
}
</script>


</head>

<div id="items">
<form name="SelectedItems" action="" method="post">
<b>Select/Unselect All</b><br>
<div style="background:#ccc;"><input name="checkall" type="checkbox" onclick="SetAllCheckBoxes('SelectedItems','items',this.checked);" /></div><br><br>

<input type="checkbox" name="selected" value="Some text description 1"><input type="hidden" name="selecteditems" value=" "><br>
<input type="checkbox" name="selected" value="Some text description 2"><input type="hidden" name="selecteditems" value=" "><br>
<input type="checkbox" name="selected" value="Some text description 3"><input type="hidden" name="selecteditems" value=" "><br>
<input type="checkbox" name="selected" value="Some text description 4"><input type="hidden" name="selecteditems" value=" "><br>
<input type="checkbox" name="selected" value="Some text description 5"><input type="hidden" name="selecteditems" value=" "><br>
<input type="checkbox" name="selected" value="Some text description 6"><input type="hidden" name="selecteditems" value=" "><br>
</div>
</form>

</body>
</html>

Jas
02-20-2008, 03:16 AM
Very good script. It seems to work very well in all browsers (couldn't see where a problem would be, but you never know). People ask for stuff like that every now and again, and it will be nice to be able to simply point them here. Good work, and please keep it up! :)