0

I want to make a check with the PHP FOREACH function something like this:

if (isset($_POST['name'])) {
        foreach ($_POST['name'] as disabled="true") {
            //do something
        }
    }

Disabled=true comes from a checkbox input that I save on submit. My question is: can I check on POST, foreach checkbox that has disabled = "true". Or in someway only do a thing if the condition hits?

Rocksteady
  • 271
  • 1
  • 4
  • 21
  • 1
    If ($_POST['name'] only consists of one value, there's no need for a foreach statement. You can just add an additional check to the IF condidtional, as follows: if (isset($_POST['name']) && isset($_POST['checkbox_name'])) { // do stuff } – Wandering Digital Jun 18 '13 at 20:35
  • why do you need to disable box if its not editable? why not a hidden value? – amigura Jun 18 '13 at 20:47
  • I want the box not to be counted if it is disabled – Rocksteady Jun 18 '13 at 20:53
  • 1
    you might have to rethink code as unchecked and disable will be the same. you might have to put disable check boxes in an array then in a hidden value. unless you don't want unchecked to be counted as well – amigura Jun 18 '13 at 21:22
  • yes maybe i should put them in an array, the unchecked boxes should not be counted. A checked box should be counted once. – Rocksteady Jun 18 '13 at 21:24

3 Answers3

1

Disabled fields are not sent to server - use readonly instead.

Also I hope you understand that foreach ($_POST['name'] as disabled="true") is not a valid php code, and you use it just as pseudocode.

zavg
  • 10,351
  • 4
  • 44
  • 67
  • yes i know that it wouldn't work, but I want something that checks if input has disabled="true" set to them, if they do I won't count that "name" – Rocksteady Jun 18 '13 at 20:52
1

if that is the case you don't want the unchecked and disables counted then that makes it a bit easier.

single check

if (isset($_POST['check2'])) 
{
     //do something
}

multiple check

$check_array=array('check1','check2','check3'); // check box names

    foreach ($check_array as $v) 
{

  if (isset($_POST[$v])) 
  {
     //do something
  }

}

<form action="" method="post">
<input name="check1" type="checkbox" disabled value="check1" checked="checked" />
<input name="check2" type="checkbox" value="check2" checked="checked" />
<input name="check3" type="checkbox" value="check3" />
<input name="" type="submit" />
</form>
amigura
  • 541
  • 3
  • 6
0

Both disabled and unchecked checkboxes don't get sent to the server so there is no way to distinguish between the two.

You could add some hidden fields an set their value with javascript depending on the user's actions.

Note that readonly does not work on checkboxes, see for example Can HTML checkboxes be set to readonly?.

Community
  • 1
  • 1
jeroen
  • 91,079
  • 21
  • 114
  • 132