php - POST 数组不显示未选中的复选框

标签 php html forms checkbox

无法让我的 POST 数组显示我表单中的所有复选框值。

我有一个表单设置如下:

<form name='foo' method='post' action=''>
    <table>
       <tr>
          <td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
      </tr>
       <tr>
          <td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
      </tr>
       <tr>
          <td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
      </tr>
   </table>
</form>

我在底部有一个按钮绑定(bind)到一个 jquery 函数,它向表单添加了 5 个空行(因此输入名称 cBox[] 的数组)。

现在,问题来了。假设第一个复选框未选中,最后两个复选框被选中。当我输出值时(使用 PHP print_r 进行调试),我将得到:

Array ( [0] => on [1] => on)

出于某种原因,该数组不包含未选中复选框的任何值。

我见过一些解决方案,其中每个复选框都传递一个隐藏变量,但是这个解决方案可以在我的情况下实现(使用数组)吗?

最佳答案

这种行为并不奇怪,因为浏览器不会为未选中的复选框提交任何值。

如果您需要以数组的形式提交准确数量的元素,为什么不执行与 id 时相同的操作呢?与每个复选框相关联的某种类型?只需将 PHP 数组键名称作为 <input> 的一部分包含在内元素名称:

  <tr>
                                                       <!-- NOTE [0] --->
      <td class='bla'>Checkbox: <input type='checkbox' name='cBox[0]'/></td>
  </tr>
   <tr>
      <td class='bla'>Checkbox: <input type='checkbox' name='cBox[1]'/></td>
  </tr>
   <tr>
      <td class='bla'>Checkbox: <input type='checkbox' name='cBox[2]'/></td>
  </tr>

这仍然会给您留下未选中的框仍然不会出现在数组中的问题。这可能是也可能不是问题。首先,您可能真的不在乎:

foreach($incoming as $key => $value) {
    // if the first $key is 1, do you care that you will never see 0?
}

即使您很在意,也可以轻松解决问题。这里有两种直接的方法。一,只做隐藏的输入元素技巧:

  <tr>
      <td class='bla'>
        <input type="hidden" name="cBox[0]" value="" />
        Checkbox: <input type='checkbox' name='cBox[0]'/>
      </td>
  </tr>
   <tr>
      <td class='bla'>
        <input type="hidden" name="cBox[1]" value="" />
        Checkbox: <input type='checkbox' name='cBox[1]'/>
      </td>
  </tr>

还有两个,我觉得更可取,用 PHP 代替填充空白:

// assume this is what comes in:
$input = array(
    '1' => 'foo',
    '3' => 'bar',
);

// set defaults: array with keys 0-4 all set to empty string
$defaults = array_fill(0, 5, '');

$input = $input + $defaults;
print_r($input);

// If you also want order, sort:

ksort($input);
print_r($input);

See it in action .

关于php - POST 数组不显示未选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988325/

相关文章:

php - CakePhp 中的严格标准错误?

php - 如何从数据库中回显 html 和 row

php - 输出 html 与使用 echo 有什么区别吗?

php - 当达到一定的购物车数量时添加促销产品

html - 如何立即将上传的图像显示为 Canvas 背景?

php - 将二维数组传递给 PHP 的 HTML 表单(我认为是特例)

javascript - 将元素上的 `display: none` 恢复为原始值

javascript - 添加多次后 Div 不起作用

c# - 在 C# ASP.NET 3.5 中更改 HtmlForm 操作

javascript - onSubmit 不适用于表单