简体   繁体   中英

Checkbox with false value in form

I need send with post false value of checkbox witch is not checked by default. My checkbox is defined like this:

<label><input type="checkbox" id="rez" name="rezerwowanie" value="false" />Rezerwowanie</label>

And after submit I use that code to check if checkbox is checked or not:

$Reservation = $_POST['rezerwowanie'];
    if ($Reservation == false) {
        $Reservation = 0;
    } else
    {
        $Reservation = 1;
    }

It work when I check the checkbox but with not checked it don't work. What's the problem here?

The checkbox only sends a value to the server when it is activated. So when it is not checked, $_POST['rezerwowanie'] will not be there. Your code will need to account for this. Checking to see if the array element isset will give you the same outcome.

$Reservation = isset($_POST['rezerwowanie']);
if ($Reservation == false) {
    $Reservation = 0;
} else
{
    $Reservation = 1;
}

A simpler way to accomplish this:

$Reservation = isset($_POST['rezerwowanie']) ? 0 : 1;

$Reservation will equal 0 if the user did not check the checkbox. I may have the logic backwards based on your needs, but the general idea is correct. No if else statement required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM