表单发布时如何获取复选框元素中未选中复选框的值?

表单发布时如何获取复选框元素中未选中复选框的值?

问题描述:

我有一个像下面这样的表格:

I have a form like below :

<form action="" method="post">
    <input type="checkbox" id="status_1" name="status_1" value="1" />
    <input type="checkbox" id="status_2" name="status_2" value="1" />
    <input type="checkbox" id="status_3" name="status_3" value="1" />
</form>

当我选中所有复选框并发布表单时,结果是这样的:

When i check all checkbox and post the form, the result is like this:

Array ([status_3] => 1 [status_2] => 1 [status_1] => 1 ) 

然后我取消选中第二个复选框并发布表单,结果如下:

Then i uncheck second checkbox and post the form, the result is like this:

Array ( [status_3] => 1 [status_1] => 1 ) 

当我取消选中第二个复选框时,是否有可能产生如下结果:

Is it possible to make result like this below when i uncheck second checkbox :

Array ( [status_3] => 1 [status_2] => 0 [status_1] => 1 ) 

有想法吗?

第一种方式 - 隐藏字段(缺点:用户可以操作字段的值(但是用户也可以操作复选框的值,所以它不是真的一个问题,如果你只期望 1 或 0))

First way - hidden fields (disadvantage: the user can manipulate the value of the field (but one can manipulate the value of the checkbox too, so it's not really a problem, if you only expect 1 or 0))

<form action="" method="post">
<input type="hidden" name="status_1" value="0" />
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="hidden" name="status_2" value="0" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="hidden" name="status_3" value="0" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
<input type="submit" />
</form>
<?php
var_dump($_POST);
/*
 * checking only the second box outputs:
 * 
 * array (size=3)
  'status_1' => string '0' (length=1)
  'status_2' => string '1' (length=1)
  'status_3' => string '0' (length=1)
 */

第二种方式 - 为非设置索引分配默认值:

Second way - to assign default value for non-set indexes:

<form action="" method="post">
<input type="checkbox" id="status_1" name="status_1" value="1" />
<input type="checkbox" id="status_2" name="status_2" value="1" />
<input type="checkbox" id="status_3" name="status_3" value="1" />
<input type="submit" />
</form>
<?php
for($i = 1; $i<=count($_POST); $i++) {
    $_POST["status_$i"] = isset($_POST["status_$i"]) ? $_POST["status_$i"] : 0;
}
var_dump($_POST);

/**
 * Here we will be checking only the third checkbox:
 * 
 * array (size=3)
  'status_3' => string '1' (length=1)
  'status_1' => int 0
  'status_2' => int 0
 */