【发布时间】:2012-11-12 15:13:18
【问题描述】:
我的表单中有 3 个(我不知道有多少可以更改。仅 3 个示例)复选框,我想在发布时使用 php 检测未选中的复选框。我该怎么做?
【问题讨论】:
我的表单中有 3 个(我不知道有多少可以更改。仅 3 个示例)复选框,我想在发布时使用 php 检测未选中的复选框。我该怎么做?
【问题讨论】:
Only checked checkboxes are submitted.所以任何未提交的复选框都是未选中的。
【讨论】:
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。
checkbox=0 和 checkbox=1 都会提交,但 $_POST 只会反映最后一个。
您可以使用以下函数完全在 PHP 中执行此检查:
function cbToBool($cb = true) {
if (isset($cb)) {
return true;
} else {
return false;
}
}
这样使用
$_POST["blocked"] = cbToBool($_POST["blocked"]);
【讨论】: