选中HTML复选框元素在提交后保持勾选

时间:2013-08-31 05:28:02

标签: php

我提交时设置了复选框,我想记住我选择的内容,我写了一段代码,但我想知道最简单的方法吗

<form action="" method="post">


                    <input type="checkbox" name="car[]"  
                        <?php 
                            if(isset($_POST['submit'])){ 
                                if(isset($_POST['car'])){
                                if(in_array('Bus',$_POST['car']))
                                    { 
                                        echo  ' checked="checked"" '; 
                                    }
                                }
                            } 
                        ?> value="Bus" />Bus
        <input type="checkbox" name="car[]" value="Van" 
                        <?php 
                            if(isset($_POST['submit']))
                            { 
                                if(isset($_POST['car'])){
                                    if(in_array('Van',$_POST['car']))
                                    { 
                                        echo  ' checked="checked"" '; 
                                    }
                                }
                            } ?> />Van

            <input type="submit" name="submit" value="Submit" />

</form>

1 个答案:

答案 0 :(得分:0)

您可以迭代车辆,并相应地打印出相应的项目(带有相应的选中值),一举。像这样的东西会起作用:

$vehicles = array('Bus', 'Van'); // You can add as many as you want!

foreach($vehicles as $vehicle) {
    // Should it be checked?
    $checked = '';
    if(isset($_POST['car'])) {
        if(in_array($vehicle,$_POST['car']) $checked="checked='checked'";
    }

    // Add the element
    echo "<input type='checkbox' name='car[]' value='{$vehicle}' {$checked}> 
        {$vehicle}";
}