【问题标题】:function empty() doesn't work on checkboxes函数 empty() 不适用于复选框
【发布时间】:2022-01-22 02:55:16
【问题描述】:

我在 html 中有这个输入

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

现在我想看看这个复选框是否在 php 中被选中

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

然而,复选框是否被选中并不重要,变量 x 总是“未选中”。为什么会发生这种情况,我该如何解决?

编辑:我也尝试使用 isset(),还是一样

【问题讨论】:

    标签: php html


    【解决方案1】:

    你有这个:

    value=""
    

    这意味着您不能使用empty() 来区分选中和未选中的复选框,因为空字符串(选中)和未定义变量(未选中)都返回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)
    

    使用您当前的有效负载,您需要检查variable existence

    $isChecked = isset($_POST['checkbox-ambulance-checked');
    

    【讨论】:

      【解决方案2】:

      您需要为复选框设置一个值(例如 value='ON')

      因为空字符串也被视为“空”(参见文档here

      改变

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

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

      所以一个样本会是这样的:

      <?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 class="form-check-input" type="checkbox" value="ON" 
      id="checkbox-ambulance" name="checkbox-ambulance">
      <br>
      <input type="submit" name="submit">
      </form>
      

      查看此示例链接

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

      【讨论】:

      • 谢谢解答,可惜还是不行
      • 请使用我发布的示例链接并尝试一下。谢谢
      • @Cristian25 为什么接受的答案有后续评论指出它不起作用?在 PHP 中分配一个不转换为 false 的值绝对是两种可能的修复方法之一。
      • 我忘了添加更新:实际上是我的代码中的错字
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      相关资源
      最近更新 更多