drbvm26000 2013-05-07 21: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-07 22: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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部