开发者

How to make a select list option selected

开发者 https://www.devze.com 2023-04-11 12:07 出处:网络
I receive a v开发者_开发技巧ariable from the mysql database named $option which in this case could be \'1\' or \'2\'. What is the correct PHP code to add the \'selected=\"selected\"\' code to $option

I receive a v开发者_开发技巧ariable from the mysql database named $option which in this case could be '1' or '2'. What is the correct PHP code to add the 'selected="selected"' code to $option 1 the corresponding option in the list?

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


<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>

like this?


This is how I would do it.

<?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>


Just add the selected property to the item you want selected.

<select name="select-list">

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

</select>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号