如何选择选择列表选项

时间:2011-10-08 18:32:48

标签: php forms

我从名为$ option的mysql数据库收到一个变量,在这种情况下可以是'1'或'2'。将'selected =“selected”'代码添加到$ option 1列表中相应选项的正确PHP代码是什么?

<select name="select-list">
<option value='1'>option 1</option>
<option value='2'>option 1</option>             
</select>

3 个答案:

答案 0 :(得分:2)

<select name="select-list">
<option value='1' <?php if ($option == '1') { echo "selected"; } ?>>option 1</option>
<option value='2' <?php if ($option == '2') { echo "selected"; } ?>">option 1</option>             
</select>
像这样?

答案 1 :(得分:0)

我就是这样做的。

<?php
    $select-list = (str) $_POST['select-list'];  //or however you retrieve this value
?>

<select name="select-list">
<option value='1' <?php if($select-list === "1"){ echo "selected"; }?>>option 1</option>
<option value='2' <?php if($select-list === "2"){ echo "selected"; }?>>option 1</option>             
</select>

答案 2 :(得分:-1)

只需将selected属性添加到要选择的项目中即可。

<select name="select-list">

    <option value='1'>option 1</option>
    <option value='2' <?php if ($option === '2') { echo "selected" } ?>>option 2</option>             

</select>