Simple Implementation of Javascript Check and Uncheck All Checkboxes

Javascript Check and Uncheck All Checkboxes

Javascript Check and Uncheck All Checkboxes



A simple example of check and uncheck all checkboxes implementation using javascript. We have created a set of checkboxes under a DIV called container. There is a checkbox at the top for check or uncheck all the checkboxes. We have added a function on the click event of top checkbox and when user click it we check its state as checked or unchecked and assign that state to all the other checkboxes.

Check out the demo here.


JavaScript Code:

<script language="javascript" type="text/javascript">
function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
   		obj.addEventListener(evType, fn, false); 
   		return true; 
 	} else if (obj.attachEvent){ 
   		var r = obj.attachEvent("on"+evType, fn); 
   		return r; 
 	} else { 
   		return false; 
 	} 
}
 
addEvent(window, 'load', initCheckboxes);
 
function initCheckboxes() {
	addEvent(document.getElementById('all'), 'click', setCheckboxes);
}
 
function setCheckboxes() {
	var cb = document.getElementById('container').getElementsByTagName('input');
 
	for (var i = 0; i < cb.length; i++) {
		cb[i].checked = document.getElementById('all').checked;
	}
}
</script>

HTML Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Check/Uncheck ALL Checkboxes</title>
<style type="text/css">
.container { width:300px}
.odd { background-color: #edf5fa;}
.even { background-color: #fff;}
.all { border-bottom:#666666 thin dashed; margin-bottom:4px;}
</style>
</head>
<body>
    <div class="container">
    	<div class="all"><label><input type="checkbox" name="cb" value="1" id="all" />Check All</label> </div>
    </div>
    <div class="container" id="container">
    	<div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Elephant</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Lion</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Tiger</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Horse</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Anaconda</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Bear</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Leopard</label> </div>
    </div>
</body>
</html>

,


  1. #1 by gajanan - June 29th, 2010 at 19:45

    it works

(will not be published)

 


Submit Comment
Subscribe to comments feed
  1. No trackbacks yet.