【问题标题】:Store a checked checkbox from a form in a session将表单中的选中复选框存储在会话中
【发布时间】:2018-02-28 00:50:06
【问题描述】:

如果用户选中该框,我想在会话中存储一个复选框值。如果是这样,也应该在重新加载页面后选中该框。如果用户取消选中该框,则应销毁会话并且必须取消选中该框。默认未选中。

我尝试了不同的代码,但没有任何效果。在我的示例中,始终检查复选框,即使用户是否选中它也是如此。

非常感谢!

我的 php:

session_start();

if( !empty($_POST['debug_on']) ) {
    $_SESSION['debug'] = true;
} else {
    $_SESSION['debug'] = false;

}

我的表格:

<form class="form-inline" name="form" method="post" action="">
<div class="form-group">
<label class="sr-only" for="inlineFormInputGroup">Email</label>
  <div class="input-group mb-2 mr-sm-2 mb-sm-0">
    <div class="input-group-addon">@</div>
    <input type="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="name@mail.com" value="<?= $email ?>" required >
  </div>
</div>

<div id="debugbox">
<label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0">
    <input type="checkbox" class="custom-control-input" name="debug_on" id="debugbox" value="1" <?php if($_SESSION['debug'] = true); echo "checked='checked'"; ?>>
    <span class="custom-control-indicator"></span>
    <span class="custom-control-description">Output debug</span>
  </label>
 </div>
<button type="submit" class="btn btn-outline-success">Submit</button>
<br>
<br>

</form>

【问题讨论】:

    标签: php session checkbox


    【解决方案1】:
            $refresh = "ok";
            if(!empty($_POST['email'])) 
            {
                $refresh ="";
            } 
    
    <input type="checkbox" class="custom-control-input" name="debug_on" id="debugbox" value="1" <?php if((isset($_SESSION['debug']) && $_SESSION['debug'] == true) || (!empty($refresh)) ) { echo "checked"; } ?> >
    

    【讨论】:

    • 谢谢,Subhash。到目前为止它可以工作,但是在重新加载页面后,该框仍然没有被选中。我想在刷新后存储 chekded 框。谢谢!
    • 使用帖子时只需检查任何随机变量并使其为空。并在同一行检查空
    • 现在该框总是被选中,即使我取消选中与否
    【解决方案2】:

    我认为问题出在这一行:echo "checked='checked'" 应该是 echo 'checked="checked"',但如果您满意,我会提出一个完整的解决方案。

    试试这个:

    session_start();
    if(!empty($_POST['debug_on'])) {
        $_SESSION['debug'] = true;
    } 
    else {
        $_SESSION['debug'] = false;
    }
    

    然后在你的 HTML 中:

    <?php print !empty($_SESSION['debug']) && $_SESSION['debug'] == true ? 'checked="checked"' : ''; ?>
    

    【讨论】:

    • 这里一样,重新加载后复选框被取消选中:(
    • @Ronny 好吧,因为我们在未发布表单时删除了会话!
    • 只要您不选中该框,它就可以工作。如果您选中该框并在提交后取消选中它,它将保持选中状态。我认为取消选中后cookie不为空。
    • 你的意思是取消勾选后,你提交表单?正确的 ?我再次更新了我的答案
    • teeyo,现在可以了。最后一件事:如何将会话存储在 cookie 中,以便在刷新页面后选中复选框?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2019-08-21
    • 2012-12-09
    • 1970-01-01
    • 2013-03-02
    • 2013-04-26
    • 1970-01-01
    相关资源
    最近更新 更多