Forum Moderators: open

Message Too Old, No Replies

select all checkboxes with names : checkbox[]

         

ayushchd

6:18 pm on Jul 31, 2007 (gmt 0)

10+ Year Member



hi

i have :

<form name="aa">
<input type="checkbox" name="ab[]" value="1">
<input type="checkbox" name="ab[]" value="2">
<input type="checkbox" name="ab[]" value="3">
<input type="checkbox" name="ab[]" value="4">
<input type="checkbox" name="ab[]" value="5">
</form>

How can I have a checkbox which when clicked checks all the checkboxes if they are not selected, and if they are selected then it disselects all the checkboxes?

I have tried this :
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[0][i].checked = true;
}
checkflag = "true";
}
else {
for (i = 0; i < field.length; i++) {
field[0][i].checked = false; }
checkflag = "false";
}
}
// End -->
</script>

This works fine when the name of the checkbox is not checkbox[] and doesnt when it is checkbox[]. And unfortunately i have to have those brackets with the names of the checkboxes as the form is being used in a php script.

Any suggestion will be welcomes.
Thanks in advance.
Ayush

Arno_Adams

7:24 am on Aug 1, 2007 (gmt 0)

10+ Year Member



Hi,

Try this


function foo() {
var boxes = document.aa.elements['ab[]'], sel = false;
for(var i=0; i<boxes.length; i++) {
if(boxes[i].checked == true) {
sel = true;
break;
}
}
for(var j=0; j<boxes.length; j++) {
(sel)? boxes[j].checked = false : boxes[j].checked = true;
}
}

HTH, AA

[edited by: Arno_Adams at 7:28 am (utc) on Aug. 1, 2007]

rocknbil

10:46 am on Aug 1, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Check 'em</title>
<script type="text/javascript">
function chkBoxes (form) {
var state;
for (i=0;i<form.elements.length;i++) {
var obj = form.elements[i];
if ((obj.type == 'checkbox') && (obj.name!= 'master')) {
state = obj.checked; // true or false
obj.checked = (state==true)?false:true;
}
}
}
</script>
</head>
<body>
<form method="" action="">
<input type="checkbox" name="master" id="master"
value="omnipresent" onClick="chkBoxes(this.form);"> Click me, I am master.
<input type="checkbox" name="check_1" id="check_1" value="1"> 1
<input type="checkbox" name="check_2" id="check_2" value="2"> 2
<input type="checkbox" name="check_3" id="check_3" value="3"> 3
<input type="checkbox" name="check_4" id="check_4" value="4"> 4
<input type="checkbox" name="check_5" id="check_5" value="5"> 5
</form>
</body>
</html>