[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
HowToJavaScript_Check_Uncheck_All_CheckBox

How to select or deselect all checkboxes?

The example shows how to allow the user to select rows of data by creating two buttons to select or unselect all checkboxes at once.

<html>
<head>
<script> 
function CheckAll()
{
count = document.frm.elements.length;
    for (i=0; i < count; i++) 
	{
    if(document.frm.elements[i].checked == 0)
    	{document.frm.elements[i].checked = 1; }
    else {document.frm.elements[i].checked = 0;}
	}
}
function UncheckAll(){
count = document.frm.elements.length;
    for (i=0; i < count; i++) 
	{
    if(document.frm.elements[i].checked == 1)
    	{document.frm.elements[i].checked = 0; }
    else {document.frm.elements[i].checked = 1;}
	}
}
</script>
</head>
<body>
<form name="form">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input name="btn" type="button" onclick="CheckAll()" value="Check All"> 
<input name="btn" type="button" onclick="UncheckAll()" value="Uncheck All"> 
</form>
</body>
</html>


The count variable will hold the value of the checkboxes' index number in the form. Each iteration will increase the index number with one. Indexes start from zero.

<form name="frm">
<input type="checkbox" /> this item will have [i] = 0
<input type="checkbox" /> this item will have [i] = 1
<input type="checkbox" /> this item will have [i] = 2
<input type="checkbox" /> this item will have [i] = 3
<input type="checkbox" /> this item will have [i] = 4 
</form>


The CheckAll() function checks if the checkboxes in the form are checked. If they aren't, then it will check all the checkboxes on the form.

The UncheckAll() function checks if the checkboxes in the form are checked. If they are, then it will uncheck all the checkboxes on the form.

Related threads:
check all button

JavaScript FAQ

last edited (April 19, 2004) by lillu, Number of views: 2455, Current Rev: 4 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.