如何使用 php 检测未选中的复选框?
我的表单中有 3 个(我不知道有多少是可以更改的.只有 3 个示例)复选框,我想在发布时使用 php 检测未选中的复选框.我该怎么做?
There are 3(I do not know how many would be it changeable. 3 only example) checkboxes in my form and I want to detect unchecked checkboxes with php when it post. How can I do this?
推荐答案
秋葵汤是对的.但是,有一个解决方法,如下所示:
Gumbo is right. There is a work around however, and that is the following:
<form action="" method="post">
<input type="hidden" name="checkbox" value="0">
<input type="checkbox" name="checkbox" value="1">
<input type="submit">
</form>
换句话说:有一个与复选框同名的隐藏字段和一个表示未选中状态的值,例如 0
.然而,重要的是让隐藏字段位于表单中的复选框之前.否则,如果复选框被选中,隐藏字段的值将在发布到后端时覆盖复选框值.
In other words: have a hidden field with the same name as the checkbox and a value that represents the unchecked state, 0
for instance. It is, however, important to have the hidden field precede the checkbox in the form. Otherwise the hidden field's value will override the checkbox value when posted to the backend, if the checkbox was checked.
另一种跟踪此情况的方法是在后端有一个可能的复选框列表(例如,甚至可以在后端使用该列表填充表单).类似下面的内容应该会给你一个想法:
Another way to keep track of this is to have a list of possible checkboxes in the back-end (and even populate the form in the back-end with that list, for instance). Something like the following should give you an idea:
<?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>
...勾选一两个复选框,然后点击提交按钮,看看会发生什么.
... check one or two checkboxes, then click the submit button and see what happens.
相关文章