views:

426

answers:

2

New to javascript, my problem is effectively: I have a php page that produces a single form with multiple process blocks or sections each with a group of checkboxes

eg

<form action='./this.php' method='POST'>
One<br>
<input type='checkbox' name='one[part1]'>a<br>
<input type='checkbox' name='one[part2]'>b<br>
<input type='checkbox' name='one[part3]'>c<br>

<input type='checkbox' name='one[all]'>all<br>
<br>
Two<br>
<input type='checkbox' name='two[part1]'>a<br>
<input type='checkbox' name='two[part2]'>b<br>
<input type='checkbox' name='two[part3]'>c<br>

<input type='checkbox' name='two[all]'>all<br>

<input type='submit'>
</form>

Example problem: I want to be able to click on the two[all] checkbox and have two[part1],two[part2], and two[part3] all become checked.

If I name all the checkboxes in the group the same, the php post value will only show up for one, so I need to keep the names different.

Is there any simple method for doing this, short of dynamically(through php) producing separate onclick functions for each section.

Note, not all sections will be the same, sometimes one.part1 may not be available for checking but its information will be shown and the checkbox names will start from b onwards.

Or maybe traversing the DOM to find all checkboxes after a start marker and before the check all.

Hopefully that is clear enough.

A: 

You need one javascript onClickAll function that takes a parameter of the group name. You can then loop through each checkbox returned by getElementsByName and mark them checked/unchecked. On the postback, you will get an array of values for the checkboxes with the group name used. By looping through, you know which was checked and which wasn't.

I'd write some sample code but its been a while since I've worked in PHP/Javascript that I think its better that someone who's better do it. But what I told you should the the gist of it. Good luck!

achinda99
Correct, code in another answer (space issue)
jim
+2  A: 

Changed the form to be more like:

<input type='checkbox' name='section[one][]' value='part1'>a<br>
<input type='checkbox' name='section[one][]' value='part2'>b<br>
<input type='checkbox' name='section[one][]' value='part3'>c<br>

<input type='checkbox' name='one[all]' onclick='checkAll(one,this)>all<br>

CheckAll function was:

function checkAll(checkid, exby) {
    boxes = document.getElementsByName('section[' + checkid + '][]');
    for (i = 0; i < boxes.length; i++){
     boxes[i].checked = exby.checked? true:false
    }
}

This ends up still giving the manageable array in the php post var while having a singular name.

jim