How can I detect unchecked checkbox with php?

心已入冬 提交于 2019-12-29 08:16:27

问题


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 do this?


回答1:


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.




回答2:


Only checked checkboxes are submitted. So any checkbox that is not submitted is unchecked.



来源:https://stackoverflow.com/questions/13542900/how-can-i-detect-unchecked-checkbox-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!