提交后保留选定的值

时间:2014-12-29 18:31:41

标签: php drop-down-menu postback

我在数组中有以下值

<?php

$selectContact = 
array(
"Services Inquiry" => "Services", 
"Product Inquiry" => "Product", 
"Training Inquiry" => "Training", 
"Careers Inquiry" => "Careers", 
"General Inquiry" => "General"
);
?>

在下拉列表中调用数组。提交表单时,我需要保留下拉菜单的选定值。

<form role="select_contact" name="selectContact" id="selectContact">
                <select>
                    <!--<option value="Select">Select</option>-->
                    <option value="Select">Select</option>
                    <?php
                        if (isset($_POST['selectContact'])) {
                            echo '<option value="'. $value .'">' . $category . '</option>';

                        } else {
                            foreach($selectContact as $category => $value) 
                            {
                               $category = htmlspecialchars($category); 
                               echo '<option value="'. $value .'">'. $category .'</option>';
                            }
                        }
                    ?>

                </select>
            </form>

1 个答案:

答案 0 :(得分:3)

您需要设置selected属性,如下所示:

<?php
    $selected = isset($_REQUEST['selectContact']) ? $_REQUEST['selectContact'] : '';
    foreach($selectContact as $category => $value) 
    {
        $category = htmlspecialchars($category); 
        echo '<option value="'. $value .'"'.(($value==$selected)?' selected':'').'>'. $category .'</option>';
    }
?>

注意:您不需要{/ 1}}分支