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>
精彩评论