There are 3(I do not know how many would be it changeable. 3 only example) checkboxes in my form and I want to detect unchecked checkboxes with php when it post. How can I d
Only checked checkboxes are submitted. So any checkbox that is not submitted is unchecked.
Gumbo is right. There is a work around however, and that is the following:
<form action="" method="post">
<input type="hidden" name="checkbox" value="0">
<input type="checkbox" name="checkbox" value="1">
<input type="submit">
</form>
In other words: have a hidden field with the same name as the checkbox and a value that represents the unchecked state, 0
for instance. It is, however, important to have the hidden field precede the checkbox in the form. Otherwise the hidden field's value will override the checkbox value when posted to the backend, if the checkbox was checked.
Another way to keep track of this is to have a list of possible checkboxes in the back-end (and even populate the form in the back-end with that list, for instance). Something like the following should give you an idea:
<?php
$checkboxes = array(
array( 'label' => 'checkbox 1 label', 'unchecked' => '0', 'checked' => '1' ),
array( 'label' => 'checkbox 2 label', 'unchecked' => '0', 'checked' => '1' ),
array( 'label' => 'checkbox 3 label', 'unchecked' => '0', 'checked' => '1' )
);
if( strtolower( $_SERVER[ 'REQUEST_METHOD' ] ) == 'post' )
{
foreach( $checkboxes as $key => $checkbox )
{
if( isset( $_POST[ 'checkbox' ][ $key ] ) && $_POST[ 'checkbox' ][ $key ] == $checkbox[ 'checked' ] )
{
echo $checkbox[ 'label' ] . ' is checked, so we use value: ' . $checkbox[ 'checked' ] . '<br>';
}
else
{
echo $checkbox[ 'label' ] . ' is not checked, so we use value: ' . $checkbox[ 'unchecked' ] . '<br>';
}
}
}
?>
<html>
<body>
<form action="" method="post">
<?php foreach( $checkboxes as $key => $checkbox ): ?>
<label><input type="checkbox" name="checkbox[<?php echo $key; ?>]" value="<?php echo $checkbox[ 'checked' ]; ?>"><?php echo $checkbox[ 'label' ]; ?></label><br>
<?php endforeach; ?>
<input type="submit">
</form>
</body>
</html>
... check one or two checkboxes, then click the submit button and see what happens.
You can do this check entirely in PHP with the following function:
function cbToBool($cb = true) {
if (isset($cb)) {
return true;
} else {
return false;
}
}
using it like this
$_POST["blocked"] = cbToBool($_POST["blocked"]);