How to make currently selected drop down menu item be preselected from database?
I tried this on my own but couldn't get it to work right. Basically I am making an edit page where a previously submitted post can be edited. On this new page the form is pre-populated with previously submitted data. One of the things that was chosen earlier was a category from a drop down. I am trying to have that previously choden category show up as the default selected one on this edit page's drop down.
<select name="categories">
<?php
// get the category the post is assigned to
$query = mysql_query("SELECT category FROM posts");
while ($row = mysql_fetch_assoc($query)) {
$chosenCategory = $row['id'];
}
// display a drop down of all categories with the chosen category preselected
$query = mysql_query("SELECT * FROM cate开发者_如何转开发gories");
while ($row = mysql_fetch_assoc($query)) {
$catId = $row['id'];
$catName = $row['name'];
if ($catId == $chosenCategory) {
$selected = "selected='selected'";
}
echo "<option value='$catId' $selected>$catName</option>\n";
}
?>
</select>
Problem with my code is it inserts the selected='selected' on every option item starting from the assigned category. I need it to just be inserted to the assigned category option.
So for example, suppose the post is assigned to a category called "baseball" here's how the current output looks:
<option value='someid'>Camping</option>
<option value='someid'>Grilling</option>
<option value='someid' selected='selected'>Baseball</option>
<option value='someid' selected='selected'>Swimming</option>
<option value='someid' selected='selected'>Extreme Frisbe</option>
<option value='someid' selected='selected'>Watching TV</option>
Where it should just start and end at baseball, instead it starts there and ends at the last menu item, so naturally that is the one that is preselected.
How to fix this?
Your code is completely correct in all ways, except you forgot to reset $selected
on every loop.
$selected = '';
if ($catId == $chosenCategory) {
$selected = "selected='selected'";
}
simply add
$selected = "";
right after the while. like this:
$query = mysql_query("SELECT * FROM categories");
while ($row = mysql_fetch_assoc($query)) {
$selected = "";
$catId = $row['id'];
$catName = $row['name'];
if ($catId == $chosenCategory) {
$selected = "selected='selected'";
}
echo "<option value='$catId' $selected>$catName</option>\n";
}
this way you "reset" selection on each iteration of the while loop
while($row = mysql_fetch_array($result)){
$preSelect = ($value == $preSelect)? "selected='selected'" : null;
echo "<option value='someValue' ".$preSelect.">SomeOption</option>";
}
精彩评论