POST数组未显示未选中的复选框

Spa*_*ter 16 html php 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>
Run Code Online (Sandbox Code Playgroud)

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

现在,问题.让我们说第一个复选框未选中,最后两个复选框被选中.当我输出值(使用PHP print_r进行调试)时,我会得到:

Array ( [0] => on [1] => on)
Run Code Online (Sandbox Code Playgroud)

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

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

Jon*_*Jon 20

这种行为并不令人惊讶,因为浏览器不会为未选中的复选框提交任何值.

如果您需要提交一个确切数量的元素作为数组,为什么不执行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>
Run Code Online (Sandbox Code Playgroud)

这仍然会让你遇到这样的问题:未经检查的框仍然不会出现在数组中.这可能是也可能不是问题.首先,你可能真的不在乎:

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

即使您关心,也可以轻松纠正问题.这里有两个简单的方法.一,只需做隐藏的输入元素技巧:

  <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>
Run Code Online (Sandbox Code Playgroud)

我认为最好的两个填充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);
Run Code Online (Sandbox Code Playgroud)

看到它在行动.


T.T*_*dua 6

一个技巧是覆盖复选框值(如果选中)。否则它的值为 0。

<form>
  <input type='hidden' value='0' name="smth">
  <input type='checkbox' value='1' name="smth">
</form>
Run Code Online (Sandbox Code Playgroud)