0

I followed the suggestion in this post: How to read if a checkbox is checked in PHP?

I am trying to get values of checkboxes in form. I have tried separating the conditionals and using them together like this, checking isset and trying to get value. Either way it always returns "NO". What am I doing wrong?

if (isset($_POST['sign']) && $_POST['sign'] == 'yes-checked-sign')  {
    $check2 = "YES";
} else {
    $check2 = "NO";
}

<input type="checkbox" name="sign" value = "yes-checked-sign" /> 
Community
  • 1
  • 1
amespower
  • 907
  • 1
  • 11
  • 25
  • 2
    Are you POSTing the form to the page with the check? – James Sep 27 '13 at 20:44
  • Try removing the spaces between value and "yes-checked-sign". – Reflic Sep 27 '13 at 20:46
  • You have more than only one checkbox, right? It's impossible, this code given, to get FALSE. You either get "YES" or "NO" – djot Sep 27 '13 at 20:50
  • 1
    checkboxes which weren't set in the form are NOT submitted with the rest of the form. you don't have to explicitly compare values: the mere presence of the checkbox's name in $_POST means it was checked. – Marc B Sep 27 '13 at 20:50
  • Thanks Reflic, I tried removing spaces, didn't make any difference. Marc B, seems like just checking and not comparing explicitly should work, but not here. – amespower Sep 27 '13 at 21:09
  • @djot, I meant "NO", not false. Sorry, since edited. – amespower Sep 27 '13 at 21:18

2 Answers2

3

Checking for isset($_POST['sign']) should be sufficient.

Make sure the checkbox is surrounded by a form element because you might be not actually POSTing it.

<form method="POST" action="foo.php">
<!-- Your checkbox goes here. -->
</form>
Community
  • 1
  • 1
federico-t
  • 12,014
  • 19
  • 67
  • 111
  • Thanks Campari. Yes the form is POSTing correctly and surrounded by the form element. I have more than one checkbox, the other one set to a different value and checked with a similar conditional. Unfortunately, isset($_POST['sign']) isn't sufficient for some reason. It's false even when checked. Thanks – amespower Sep 27 '13 at 21:05
0

For checking if checkbox is checked:

if (isset($_POST['sign']))  {
    $check2 = "YES";
} else {
    $check2 = "NO";
}

Form with pre-checked checkbox:

<form method="post">
    <input type="checkbox" name="sign" checked/>
    <input type="submit" value="submit"/>
</form>

Hope this helps.