Page 1 of 1

checkbox array

Posted: Mon May 30, 2005 2:29 am
by harrisonad
I am searching for this topic but i am not satisfied with their solutions.
Here is my problem:
I have an array of checkboxes with the same name 'appid'. Now if i will submit this one, how will my script receive them since they are an array.
is it ...

Code: Select all

$app_arrays = $_POST['appid'];
I have tried this one but it only gives the last checkbox that are checked by the user.
Anyone?

Posted: Mon May 30, 2005 2:48 am
by Chris Corbyn
Show the other page where the checkboxes are please.

Posted: Mon May 30, 2005 2:55 am
by harrisonad
Actually I used db to create it

Code: Select all

while($data = mysql_fetch_array($result)){
$id = $data['id'];
echo "<td><input type=checkbox name=app value=$id></td>";
}

Posted: Mon May 30, 2005 3:52 am
by Chris Corbyn
There's only ever going to be one $_POST['app'] because you overwrite it each time your loop (which ever is the bottom one ticked witll show on the other side).

Use unique names (e.g. app1, app2, app3 etc).

Posted: Mon May 30, 2005 4:08 am
by harrisonad
I found the solution from google search. If i put brackets in the name attribute i can access it in php as array.

Code: Select all

echo "<input type=chekbox name='appid[]' value=$appid>";
// accessed in php script like this 
$aray = $_POST['appid'];
foreach($aray as $name=>$value){
But my problem is whenever i try to use javascript to validate this checkboxes, like

Code: Select all

echo "
<script language='javascript'>
var len = document.myform.appid.length;
</script>";
It will produce an error saying "appid.length is null".
Please help me with this.

Posted: Mon May 30, 2005 9:20 am
by phpScott
that is when your friend the id comes in. use the same id on all your checkboxes in a group then use document.getElementById['idname'] as an array in js.

Posted: Mon May 30, 2005 11:20 am
by Burrito

Code: Select all

for (i=0; i < document.getElementsByName('yourcheckboxname&#1111;]').length; i++){
     document.getElementsByName('yourcheckboxname&#1111;]').item(i).checked = true;
}
this will check all of them in the array, but you could do whatever you wanted...ie check to see if they are all checked and if not, break the loop etc.