当表单提交如何获取复选框中选中的元素值复选框? [英] How get value for unchecked checkbox in checkbox elements when form posted?
问题描述
我有一个表格如下图所示:
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
*/
这篇关于当表单提交如何获取复选框中选中的元素值复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!