Thursday, March 12, 2009

Select All / None Checkboxes

In the below example you will know how to enable all the checkboxes by using single click and how to disable the checkboxes by using a single click. These functionality is used when we need to delete all the records in a single page. The best usage of using this exampe is "In yahoo mail where we need to provide user to check all the read mail and delete"

<html>
<head>
<SCRIPT LANGUAGE="JavaScript">

function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}

</script>

</head>
<body>
<form name="myform" action="test2.html" method="post">
<b>Your Favorite Scripts & Languages</b><br>
<input type="checkbox" name="list" value="1">Java<br>
<input type="checkbox" name="list" value="2">Javascript<br>
<input type="checkbox" name="list" value="3">Active Server Pages<br>
<input type="checkbox" name="list" value="4">HTML<br>
<input type="checkbox" name="list" value="5">SQL<br>

<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.myform.list)">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.myform.list)">
<br>
</form>
</body>
</html>


Here when we click on the check All function all the checkboxes are selected and when the uncheckAll() function is selected then all the checkboxes are deselected


If you want to use a single button to checkall and uncheck all use the below code

<html>
<head>

<script language="javascript">

checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>

</head>
<body>
<form id ="frm1">
<input type="checkbox" name="chk1">
<input type="checkbox" name="chk2">
<input type="checkbox" name="chk3">
<input type="checkbox" name="chk4">
<input type="checkbox" name="chk5">
<input type='button' name='checkall' value="check/uncheck" onclick='checkedAll(frm1);'>
</form>
</body>
</html>

No comments:

Post a Comment