Forum Moderators: coopster

Message Too Old, No Replies

php $ POST method and checkboxes

finding out which checkboxes were checked from a $_POST method.

         

jpl80

3:06 pm on May 14, 2007 (gmt 0)

10+ Year Member



I have a MySQL query that returns an array of results. I have a loop that makes a checkbox for every result in the array. When the form is submitted, I need to figure out which checkboxes were clicked. How do I do that?

In summation: I can get the value of EVERY checkbox, but I only want the ones that were checked. This is my code that gets the value of every checkbox:


$result = count($_POST["id"]);
print "$result in the array\n";
for ($i=0; $i < $result; $i++) {
print $_POST["id"][$i]."\n";
}

joelgreen

3:16 pm on May 14, 2007 (gmt 0)

10+ Year Member



Browsers return "on" only for checked checkboxes. Non-checked are completely ignored and not included in the POST.

I'm coding it like this.

<input name="mycheckbox[10]" type="checkbox" /> - assume it is checked
<input name="mycheckbox[20]" type="checkbox" /> - assume it is NOT checked
<input name="mycheckbox[25]" type="checkbox" /> - assume it is checked

PHP:

$checked = $_POST['mycheckbox'];

foreach($checked as $item) {
echo "Item $item was checked<br />";
}

Output would be:
Item 10 was checked
Item 25 was checked

jpl80

3:44 pm on May 14, 2007 (gmt 0)

10+ Year Member



That worked. thank you very much. Stupid mistake on my part. Future advice to noobs, make sure you're trying to get the value from the name attribute in the checkbox tag only. Duh!

<input type='checkbox' name='id[]' value='$x' />