drbvm26000 2013-05-08 05:58
浏览 53
已采纳

使用php通过复选框进行表单验证

<?
$val="";
if(isset($_POST['save']))   
{
    if(isset($_POST['color']))
    {
        $color=$_POST['color'];
        foreach($color as $val)
        {
            echo $val."<br>";
        }
    }
}

?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form method="post">
<input type="checkbox" name="color[]" value="blue" <? if($val=='blue'){ echo "checked"; }?> />Blue
<input type="checkbox" name="color[]" value="red"<? if($val=='red'){ echo "checked"; }?> />Red
<input type="checkbox" name="color[]" value="green"<? if($val=='green'){ echo "checked"; }?>/>Green
<input type="checkbox" name="color[]" value="yellow"<? if($val=='yellow'){ echo "checked"; }?>/>Yellow
<input type="checkbox" name="color[]" value="white"<? if($val=='white'){ echo "checked"; }?>/>White

<input type="submit" name="save">
</form>
</body>
</html>

When I select one checkbox, then I click "save", the check box is checked and the colour is visible on top.
But, when I select more than one check box, then I click "save", only one checkbox is checked, but the colours are visible on the top.

So I need my code to keep the checkbox checked and have the colours remain the same. E.g. When I select red, green, yellow check box, after I click "save", it should be "CHECKED".

  • 写回答

1条回答 默认 最新

  • douyi9597 2013-05-08 06:05
    关注

    That's because you're overwriting the value of $val each time the loop executes, so it will only ever contain the last one. You would need to assign them to an array - something like:

    $selected = array();
    ...
    foreach($color as $val)
    {
        $selected[] = $val;
        echo $val."<br>";
    }
    ...
    <input type="checkbox" name="color[]" value="blue" <? if(in_array('blue',$selected)) echo "checked"; ?> />Blue
    // and so on
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条