【问题标题】:Keeping a Checkbox checked in a checkbox group if error on submit PHP如果提交 PHP 时出错,请在复选框组中选中复选框
【发布时间】:2015-03-04 04:39:26
【问题描述】:

我有一组复选框,当出现提交错误时,我需要保持它们处于选中状态。如果没有进行选择,它会验证并显示错误,但如果它回发,则不会保持选中的框。

HTML

<div class="fieldBox">
<div class="label"><p class="bold">Special Needs</p></div>
<div class="field"><?php echo $snMessage; ?>
<input type="checkbox" id="none" value="None" name="sNeeds[None]" <?php   echo(in_array('None',$sNeeds))?'checked="checked"':'';?> /><label for="none">   <span></span>None</label>
<input type="checkbox" id="IEP" value="IEP" name="sNeeds[IEP]" <?php echo(in_array('IEP',$sNeeds))?'checked="checked"':'';?> /><label for="IEP"><span></span>IEP</label>
<input type="checkbox" id="405" value="405" name="sNeeds[405]" <?php echo(in_array('405',$sNeeds))?'checked="checked"':'';?> /><label for="405"><span></span>405</label>
</div>
</div> 

PHP

$sNeeds = array('None', 'IEP', '405');
//Check Special Needs
if(empty($_POST['sNeeds'])) {
    $snMessage .= '<p class="errorClass">Required</p>';
}

我哪里做错了?提前感谢您的宝贵时间!

【问题讨论】:

  • PHP 在外部 PHP 页面中

标签: php html checkbox


【解决方案1】:
// start session in your form page
<?php session_start(); ?>

    <input type="checkbox" id="none" value="None" name="sNeeds[]" <?php   echo(in_array('None',$_SESSION['form_values']))?'checked="checked"':'';?> /><label for="none">   <span></span>None</label>
    <input type="checkbox" id="IEP" value="IEP" name="sNeeds[]" <?php echo(in_array('IEP',$_SESSION['form_values']))?'checked="checked"':'';?> /><label for="IEP"><span></span>IEP</label>
    <input type="checkbox" id="405" value="405" name="sNeeds[]" <?php echo(in_array('405',$_SESSION['form_values']))?'checked="checked"':'';?> /><label for="405"><span></span>405</label>

在你的 php 代码中保存 $_POST 以防验证失败

<?php session_start();

if (validation_fails)
{
  $_SESSION['form_values'] = $_POST['sNeeds'];
  header("location: yourformpage.php");
}

【讨论】:

  • 我应该提到并且直到您发表评论才想到它,但是 PHP 在外部页面中。
猜你喜欢
  • 2015-09-30
  • 2013-12-06
  • 1970-01-01
  • 2014-09-20
  • 2016-01-21
  • 1970-01-01
  • 2014-06-12
  • 1970-01-01
  • 2012-05-23
相关资源
最近更新 更多