PDA

View Full Version : Check all / uncheck all checkboxes - cross browser


mark wills
01-07-2003, 02:35 PM
Hi there. I am an ASP programmer, I know nothing about JavaScript - I am a terrible JavaScript programmer.

I was searching www.javascriptkit.com for a script that I could use to search out all HTML objects and if thier type was CHECKBOX then either select them all, or deselect them all (seperate links/buttons for check/uncheck is fine).

Sadly I was unable to find anything suitable. It struck me that this is something that must have been done before, and I was wondering if anyone had the answer to it... I imagine the code would have to go something like this: (remember - I'm an ASP guy - this is pseudo code!!)

Sub CheckUnCheck(Status as Boolean)
For Each HTMLObj in HTMLPage
If HTMLObj.Type="checkbox" Then
HTMLObj.Checked=Status
End If
Next
End Sub

The above (psuedo) code would allow you to pass a TRUE or FALSE in and either check, or uncheck all the checkboxes on a form.

The trouble is, I need to implement this in JavaScript, and preferable have it run in both IE and Netscape.

Any ideas where I could find some script that may fit the bill?

Many thanks,

Mark Wills.

mark wills
01-07-2003, 03:02 PM
I hacked the JavaScriptKit.com script that looked for all objects of a particular name, and managed to change it so that it works by type instead. I just tested it in IE, Netscape, and Opera, and it works fine :)

Here's the code, in case anyone is interested.


<html>
<head>
<script>
function checkall(formname,checkname,thestate){
var el_collection=eval("document.forms."+formname)
for (c=0;c<el_collection.length;c++)
{
if(el_collection[c].type=='checkbox') el_collection[c].checked=thestate;
}

}

</script>
</head>
<body>
<form name="test">
<input type="checkbox" name="v21"> Peter<br>
<input type="checkbox" name="v172"> Jane<br>
<input type="checkbox" name="v17"> George<br>
<input type=text name=mytext>
</form>

<!-- checkall(name of form, common name of checkbox group, true or false)-->

<a href="javascript:checkall('test','v1',true)">Check All</a><br>
<a href="javascript:checkall('test','v1',false)">Uncheck All</a>
</body>
</html>