PDA

View Full Version : Checkall functionality using javascript to check all checkboxes



goldalushington
03-14-2010, 01:53 AM
I have an array of check boxes and I would like to use javascript to check all when I check this one box.How is this possible?

jscheuer1
03-14-2010, 05:43 AM
In about the simplest terms:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function checkall(el){
var ip = document.getElementsByTagName('input'), i = ip.length - 1;
for (i; i > -1; --i){
if(ip[i].type && ip[i].type.toLowerCase() === 'checkbox'){
ip[i].checked = el.checked;
}
}
}
</script>
</head>
<body>
<input type="checkbox" value=""><br>
<input type="checkbox" value=""><br>
<input type="checkbox" value=""><br>
<input type="checkbox" value=""><br>
<input type="checkbox" value=""><br>
<label>Check All: <input type="checkbox" value="" onclick="checkall(this);"></label><br>
</body>
</html>

Note: This can be tweaked if need be. Like, if there are other checkboxes on the page and you want to limit it to certain ones:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function checkall(el){
var ip = document.getElementById('theboxes').getElementsByTagName('input'), i = ip.length - 1;
for (i; i > -1; --i){
if(ip[i].type && ip[i].type.toLowerCase() === 'checkbox'){
ip[i].checked = el.checked;
}
}
}
</script>
</head>
<body>
<div id="theboxes">Included:<br>
<input type="checkbox" value=""><br>
<input type="checkbox" value=""><br>
<input type="checkbox" value=""><br>
<input type="checkbox" value=""><br>
<input type="checkbox" value=""><br>
<label>Check All: <input type="checkbox" value="" onclick="checkall(this);"></label>
</div>
<hr>
Other: <input type="checkbox" value=""><br>
</body>
</html>

There are various ways.

goldalushington
03-14-2010, 02:49 PM
Thank you I'll try it.