实现多选,可以使用input 的checkbox来完成,只不过checkbox的name属性要设置为一样并且使用array数组形式命名。比如:

Mexican<input type=\"checkbox\" name=\"food[]\" value=\"Mexican\" />
Italian<input type=\"checkbox\" name=\"food[]\" value=\"Italian\" />
Chinese<input type=\"checkbox\" name=\"food[]\" value=\"Chinese\" />

上面实例代码就可以实现多选。

多选框实现后,那么该如何通过php处理多选框的值呢?

其实,通过表单提交的多选框的值是一个数组,比如上面的实例,如果我们将这三个checkbox都选中,然后提交表单,这个时候在php页面接收提交表单的多选框的值是数组.

array(\'Mexican\',\'Italian\',\'Chinese\');

因此在php处理页面,我们只需要处理这个数组就行了。

下面代码是使用checkbox实现多选框并在php页面处理多选框值的实例:

<html>
<head>
    < >Using Default Checkbox Values</ >
</head>
<body>
<?php
$food = $_GET[\"food\"];
if (!empty($food)){
    echo \"The foods selected are: <strong>\";
    foreach($food as $foodstuff){
        echo \'<br />\'.htmlentities($foodstuff);
    }
    echo \"</strong>.\";
}
else {
    echo (\'
    <form action=\"\'. htmlentities($_SERVER[\"PHP_SELF\"]).\'\" method=\"GET\">
        <fieldset>
            <label>
                Italian
                <input type=\"checkbox\" name=\"food[]\" value=\"Italian\" />
            </label>
            <label>
                Mexican
                <input type=\"checkbox\" name=\"food[]\" value=\"Mexican\" />
            </label>
            <label>
                Chinese
                <input type=\"checkbox\" name=\"food[]\" value=\"Chinese\" checked=\"checked\" />
            </label>
        </fieldset>
        <input type=\"submit\" value=\"Go!\" />
    </form> \');
    }
?>
</body>
</html>
  

 

收藏 打印