Page 1 of 1

check/uncheck all button

Posted: Mon Aug 22, 2005 8:46 pm
by s.dot
I got the following code from thejavascriptsource.com

Code: Select all

<SCRIPT type="text/javascript">
<!--
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;}
checkflag = "true";
return "Uncheck All"; }
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false; }
checkflag = "false";
return "Check All"; }
}
//-->
</script>
Then I place this on my form where you can check/uncheck all of the checkboxes

Code: Select all

<input type=button value="Check All" onClick="this.value=check(this.form.delmessageid)">
The name of the checkboxes are actually delmessageid[] but if I put that in there, it says "syntax error". Currently the way it works is when you click it, the error is "length is null or not an object". I'm guessing that's because I didn't add the [] on to the name of my field. How can I get around this to make this work properly?

Posted: Mon Aug 22, 2005 9:09 pm
by feyd
checkboxes don't have a length property, from what I remember. You'll have to iterate over them. You can uniquely name them, or just iterate over their offsets in the form's elements array...

Posted: Mon Aug 22, 2005 9:47 pm
by s.dot
The code works fine with the checkbox names being delmessageid , but I need them as delmessageid[] so I can pass the values in an array

When I do this I get a "syntax error" on "onClick="function(this.form.delmessageid[]);"

Posted: Mon Aug 22, 2005 9:58 pm
by feyd
it's not a legal object name you can reference like the normal name. As I said, iterate over the elements of the array. You could also use unique id's and use getElementById()

Posted: Mon Aug 22, 2005 10:41 pm
by s.dot
I gave the checkbox field an ID --> <input id="checkbox" name="delmessageid">

then I used onClick="checkAll(document.getElementById('checkbox'));"

then the javascript is this:

Code: Select all

function checkAll(field)
{
for (i = 0; i < 25; i++)
	document.getElementById("checkbox").checked = true ;
}
This checks the first one only and doesn't appear to be looping.

Posted: Mon Aug 22, 2005 11:15 pm
by feyd
they all have the same ID, getElementById will only fetch the first one it finds. As I said, name them all uniquely or just iterate the elements array of the form object.

Posted: Tue Aug 23, 2005 5:11 am
by raghavan20
this is not the solution, this can tell you how to do it...
http://javascript.internet.com/buttons/check-all.html