Home > Software engineering >  function empty() doesn't work on checkboxes
function empty() doesn't work on checkboxes

Time:01-23

I have this input in html

<input  type="checkbox" value="" id="checkbox-ambulance" name="checkbox-ambulance">

Now I want to see if the checkbox is checked in php with this

if (empty($_POST['checkbox-ambulance'])) {
   $x = "unchecked";
} else {
   $x = "checked";
}

However, it doesn't matter if the checkbox is checked or not, the variable x is always gonna be "unchecked". Why does this happen and how can I fix it?

EDIT: I also tried to use isset(), still the same

CodePudding user response:

You need to have a value for the checkbox (e.g. value='ON')

Because empty string is also regarded as "empty" (see the documentation here )

Change

<input  type="checkbox" value="" 
id="checkbox-ambulance" name="checkbox-ambulance">

to

<input  type="checkbox" value="ON" 
id="checkbox-ambulance" name="checkbox-ambulance">

So a sample will be like:

<?php

if ($_POST["submit"]) {

if (empty($_POST['checkbox-ambulance'])) {
   $x = "unchecked";
} else {
   $x = "checked";
}

echo $x; 
echo "<br>";
echo date('l jS \of F Y h:i:s A');

}
?>

<form action=# method=POST>
Tick this box (or not):
<input  type="checkbox" value="ON" 
id="checkbox-ambulance" name="checkbox-ambulance">
<br>
<input type="submit" name="submit">
</form>

See this sample link:

http://www.createchhk.com/SO/testSO22Jan2022.php#

CodePudding user response:

You have this:

value=""

That means that you cannot use empty() to distinguish between checked and unchecked checkboxes because both empty strings (checked) and undefined variables (unchecked) return false:

<form method="post">
    <input type="checkbox" value="" name="checkbox-ambulance-checked" checked>
    <input type="checkbox" value="" name="checkbox-ambulance-unchecked">
    <button>Submit</button>
</form>
var_dump($_POST);
array(1) {
  ["checkbox-ambulance-checked"]=>
  string(0) ""
}
var_dump(empty(''), empty($variable_that_does_not_exist));
bool(true)
bool(true)

With your current payload, you need to check for variable existence:

$isChecked = isset($_POST['checkbox-ambulance-checked');
  •  Tags:  
  • Related