# Checkbox group in javascript & PHP



## thinkdigit (Sep 14, 2008)

A series of checkbox elements are generated on the fly depending on the table contents and their number is unknown. The group of checkboxes are given the same name say name="chkb". I use the following code to toggle between select all and deselect all.


```
function check(cl){
	if(document.getElementById('c1').checked == true){
		for(i=0;i<cl.length;i++){
			cl[i].checked = true;
		}
	}else{
		for(i=0;i<cl.length;i++){
			cl[i].checked = false;
		}
	}
}
```
When the user submits, I'd like to know how many were checked. The same code can be tweaked for this purpose.

When the form is submitted only one checkbox value is available in $_POST array even if all are checked. This is probably because the checkbox group must be renamed differently such as name="chkb[]" and can be accessed later using

```
foreach($_POST['chkb'] as $cd)
```
If the checkboxes are named as chkb[], then the above javascript fails. How do I get around this problem?


----------



## JimmySeal (Sep 25, 2007)

I'm assuming cl will be a single checkbox in this situation.
Please try this:


```
function check(cl){
       [B][I]var checkboxes = document.getElementsByName("chkb[]");[/I][/B]
	if(document.getElementById('c1').checked == true){
		for(i=0;i<[B][I]checkboxes[/I][/B].length;i++){
			[B][I]checkboxes[/I][/B][i].checked = true;
		}
	}else{
		for(i=0;i<[B][I]checkboxes[/I][/B].length;i++){
			[B][I]checkboxes[/I][/B][i].checked = false;
		}
	}
}
```


----------

