PHP如何从下拉菜单中保留所选选项,以便在提交时保持选中状态? [英] PHP How can I keep the selected option from a drop down to stay selected on submit?

查看:403
本文介绍了PHP如何从下拉菜单中保留所选选项,以便在提交时保持选中状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

<select name="topic" style="margin-bottom:3px;"> 
    <option>General Question</option>
    <option>Company Information</option>
    <option>Customer Issue</option>
    <option>Supplier Issue</option>
    <option>Request For Quote</option>
    <option>Other</option>
</select>

。提交表单后,它会转到验证页面。如果有错误,则表单将保留用户输入的原始内容。我可以将其用于所有输入字段和文本区域,但是如何下拉菜单呢?

for the drop down. And when the form is submitted, It goes to a validation page. If it has errors the form keeps the original content the user put in. I have it working for all of the input fields and textarea's, but how could I do this with a drop down?

我使用以下命令保留输入字段:

I have the input fields staying by using:

$name = $_REQUEST["name"];

,并且在再次显示的形式中,存在(忽略表中的事实):

and in the form that shows up again, there is (ignore the fact that it is in a table):

<tr>
    <td>Name:*</td>
     </tr>
     <tr>
    <td><input name="name" type="text" size="15" value="<?php echo $name ?>" maxlength="200" /></td>
     </tr>

那么,对于下拉菜单有什么想法吗?

So, any ideas for drop downs?

推荐答案

您需要将 selected属性添加到适当的选项。我相信您还需要为每个选项指定value属性。我不知道您是如何生成该列表的,但是也许这会有所帮助:

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>

这篇关于PHP如何从下拉菜单中保留所选选项,以便在提交时保持选中状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆