How can I detect unchecked checkbox with php?

前端 未结 3 1397
失恋的感觉
失恋的感觉 2020-12-20 03:18

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

3条回答
  •  感情败类
    2020-12-20 04:06

    Gumbo is right. There is a work around however, and that is the following:

    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:

     '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' ] . '
    '; } else { echo $checkbox[ 'label' ] . ' is not checked, so we use value: ' . $checkbox[ 'unchecked' ] . '
    '; } } } ?>
    $checkbox ): ?>

    ... check one or two checkboxes, then click the submit button and see what happens.

提交回复
热议问题