当检查默认状态时如何记住复选框状态? [英] How to remember checkbox state when default state is checked?

查看:187
本文介绍了当检查默认状态时如何记住复选框状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有复选框的表单。



该复选框有三个状态:


  1. 选择为默认。

  2. 未被用户选中。


我该如何做?如果我使用!isset(),我可以取消选中复选框,但它不区分是否未被用户勾选或者假设被默认选中。 / p>

我想使用这个来填充表单输入的最后一个值,只要提交时有表单错误。



当复选框的默认状态未选中时,很容易做到。我可以这样做:

  if(isset($ _ POST ['checkbox']))echo'checked' //复选框已选中


解决方案

在提交后维护表单的状态是使用数组来存储输入值。首先设置默认值,然后如果表单已提交,则使用提交的内容覆盖默认值。在HTML表单中,始终从表单数组输出值。

  //创建数组保持提交的值)
$ form = array(
'myCheckbox'=> true //默认检查
'firstName'=>'',


//提交的表单?
if($ _ SERVER ['REQUEST_METHOD'] =='POST'){
//覆盖表单数组
$ form ['myCheckbox'] = isset($ _ POST ['myCheckbox' ]);
$ form ['firstName'] = $ _POST ['firstName'];

//此时进行任何验证,如果失败,请按以下格式显示
}

现在查看表单:

 < form method =post> 
< input type =checkboxname =myCheckboxvalue =1<?php echo $ form ['myCheckbox']? 'checked':''?> />
< input type =textname =firstNamevalue =<?php echo htmlspecialchars($ form ['firstName']);?" />
< / form>

在上面,我添加了一个文本输入 firstName 来说明所有的表单输入都应该由数组管理。


I have a form with a check box.

The check box has three "states":

  1. Checked as default.
  2. Unchecked by user.
  3. Checked again by user.

How would I do something like that? If I use !isset(), I can uncheck the checkbox but it doesn't distinguish if it was unchecked by the user or if it's suppose to be checked as default.

I want to use this to refill the last values of the form inputs whenever there are form errors on submit.

It's easy to do when the default state of the check box is unchecked. I can then just do:

if (isset($_POST['checkbox'])) echo ' checked'; //check box has been checked

解决方案

The cleanest way of maintaining the form's state after submission is to use an array to store the input values. First you set the default values, then if the form has been submitted, overwrite the defaults with whatever was submitted. In the HTML form, always output the value from the form array.

// 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
}

Now for the form:

<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>

In the above, I added a text input firstName to illustrate that all of the form inputs should be managed by the array.

这篇关于当检查默认状态时如何记住复选框状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆