我有一个带有复选框的表单。
该复选框具有三种“状态”:
- 默认选中。
- 未由用户选中。
- 由用户再次检查。
我该如何做这样的事情?如果我使用 !isset()
,我可以取消选中该复选框,但它无法区分它是否被用户取消选中,或者是否默认被选中。
每当提交时出现表单错误时,我想用它来重新填充表单输入的最后一个值。
当复选框的默认状态为未选中时,这很容易做到。然后我可以这样做:
if (isset($_POST['checkbox'])) echo ' checked'; //check box has been checked
最佳答案
提交后维护表单状态的最简洁方法是使用数组来存储输入值。首先设置默认值,然后如果表单已提交,则用提交的内容覆盖默认值。在 HTML 表单中,始终输出表单数组中的值。
// create the array (for both viewing the form and maintaining the submitted values)
$form = array(
'myCheckbox' => true // default to checked
'firstName' => '',
)
// was the form submitted?
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// overwrite the form array
$form['myCheckbox'] = isset($_POST['myCheckbox']);
$form['firstName'] = $_POST['firstName'];
// at this point do any validation, if it fails, let the form show
}
现在表格:
<form method="post">
<input type="checkbox" name="myCheckbox" value="1" <?php echo $form['myCheckbox'] ? 'checked' : '' ?> />
<input type="text" name="firstName" value="<?php echo htmlspecialchars($form['firstName']); ?>" />
</form>
在上面,我添加了一个文本输入 firstName
来说明所有表单输入都应该由数组管理。
关于php - 当默认状态被选中时如何记住复选框状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23570752/