問題描述
我的表單中有 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 檢測未選中的復選框?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!