PHP How can I keep the selected option from a drop down to stay selected on submit?

跟風遠走 提交于 2019-12-02 10:28:00

You need to add the "selected" attribute to the appropriate option. I believe you also need to specify the value attribute for each option. I don't know exactly how you are generating that list, but maybe this will help:

<?php
$options = array( 1=>'General Question', 'Company Information', 'Customer Issue', 'Supplier Issue', 'Supplier Issue', 'Request For Quote', 'Other' );
$topic = $_REQUEST['topic']; // the topic name would now be $options[$topic]

// other PHP etc...
?>

<select name="topic" style="margin-bottom:3px;"> 
    <?php foreach ( $options as $i=>$opt ) : ?>
        <option value="<?php echo $i?>" <?php echo $i == $topic ? 'selected' : ''?>><?php echo $opt ?></option>
    <?php endforeach; ?>
</select>

First of all, give the option element a value attribute. This makes the code more robust, because it does not break should you decide to alter the text of an option. After that:

<?php $topic = $_REQUEST['topic']; ?>
<?php $attr = 'selected="selected"'; ?>
<select name="topic" style="margin-bottom:3px;"> 
    <option value="1" <?php echo $topic == 1 ? $attr : ''; ?>>General Question</option>
    <option value="2" <?php echo $topic == 2 ? $attr : ''; ?>>Company Information</option>
    <option value="3" <?php echo $topic == 3 ? $attr : ''; ?>>Customer Issue</option>
    <option value="4" <?php echo $topic == 4 ? $attr : ''; ?>>Supplier Issue</option>
    <option value="5" <?php echo $topic == 5 ? $attr : ''; ?>>Request For Quote</option>
    <option value="6" <?php echo $topic == 6 ? $attr : ''; ?>>Other</option>
</select>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!