【问题标题】:How can I detect unchecked checkbox with php?如何使用 php 检测未选中的复选框?
【发布时间】:2012-11-12 15:13:18
【问题描述】:

我的表单中有 3 个(我不知道有多少可以更改。仅 3 个示例)复选框,我想在发布时使用 php 检测未选中的复选框。我该怎么做?

【问题讨论】:

    标签: php checkbox


    【解决方案1】:

    Only checked checkboxes are submitted.所以任何未提交的复选框都是未选中的。

    【讨论】:

      【解决方案2】:

      Gumbo is right。然而,有一种解决方法,如下所示:

      <form action="" method="post">
          <input type="hidden" name="checkbox" value="0">
          <input type="checkbox" name="checkbox" value="1">
          <input type="submit">
      </form>
      

      换句话说:有一个与复选框同名的隐藏字段和一个表示未选中状态的值,例如0。然而,重要的是让隐藏字段表单中的复选框之前。否则,如果复选框被选中,隐藏字段的值将在发布到后端时覆盖复选框值。

      另一种跟踪这一点的方法是在后端有一个可能的复选框列表(例如,甚至在后端的表单中填充该列表)。像下面这样的东西应该会给你一个想法:

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

      ...选中一两个复选框,然后单击提交按钮,看看会发生什么。

      【讨论】:

      • 谢谢,那有没有办法检测到呢?
      • 不是没有我的例子,或者没有跟踪后端的复选框。如果复选框未选中,我的示例将 $_POST['checkbox'] 的隐藏值提交 0,否则提交 1
      • @fireeyedboy 实际上,checkbox=0checkbox=1 都会提交,但 $_POST 只会反映最后一个。
      • @Gumbo 我认为你的意思是当复选框被选中时?在这种情况下,你确实是对的。
      • @prestack 我为您添加了一个示例,说明如何跟踪后端的复选框并在提交表单时确定它们的状态。
      【解决方案3】:

      您可以使用以下函数完全在 PHP 中执行此检查:

      function cbToBool($cb = true) {
          if (isset($cb)) {
              return true;
          } else {
              return false;
          }
      }
      

      这样使用

      $_POST["blocked"] = cbToBool($_POST["blocked"]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-18
        • 1970-01-01
        相关资源
        最近更新 更多