How can I detect unchecked checkbox with php?(如何使用 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.
这篇关于如何使用 php 检测未选中的复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 php 检测未选中的复选框?
基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01