简体   繁体   English

动态下拉框的预选值

[英]pre-selected values for a dynamic drop-down box

Here is my problem, I have dropdown which used to save the selected option to a SQL database. 这是我的问题,我有一个下拉菜单,用于将所选选项保存到SQL数据库。 Now I have an Edit option where the same dropdown is created dynamically to give the user to select and alternate option and save the edit. 现在,我有了一个“编辑”选项,其中动态创建了相同的下拉菜单,以使用户可以选择和替换选项并保存编辑。 When the edit page launches I want the dropdown to be pre-selected the value already saved in the database. 当编辑页面启动时,我希望下拉列表预先选择已经保存在数据库中的值。

I use following code to get done the similar thing with a textbox but strugling to put the same value attribute to the dropdown. 我使用以下代码通过文本框完成了类似的操作,但努力将相同的value属性添加到下拉列表中。

 <input name='routename' type='text'  value='".htmlentities($row['route'])."'> // This is working for the textbox

can someone tell me how to do this with a dropdown box? 有人可以告诉我如何使用下拉框吗? Thanks 谢谢

It's a little more complicated but can be achieved with this: 稍微复杂一点,但是可以通过以下方式实现:

<select name="something">
    <option value="1"<?=($row['something'] == 1)? ' selected="selected"':''?>>Option 1</option>
    <option value="2"<?=($row['something'] == 2)? ' selected="selected"':''?>>Option 2</option>
</select>

You will have to use conditional code as you generate your <option> nodes like this: 生成<option>节点时,您将必须使用条件代码,如下所示:

<?php
echo '<option ';
if ($value == $selected_value)
    echo 'selected="selected"';
echo 'value="'.htmlspecialchars($value).'" />';
?>
while($row=mysql_fetch_row($rs)){

if($row['id']==$value){
   $selected='selected';
}else{
    $selected='';
}

echo '<option value="$row['id']" $selected >$row['value']</option>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM