Reputation:
When I select a value in this dropdown, a javascript function will work and it will give a GET value to URL. Now I want to give that selected value as selected in this dropdown list. How to do that?
<?php while ($row = mysql_fetch_array($res)) { echo '<option value='.$row["id"].'>'.$row["name"].'</option>';}?>
Upvotes: 0
Views: 2831
Reputation: 21
Fetch selected value from GET request to compare with each id and put selected attribute in option tag to make it selected by default.
e.g.
<select name="id">
<?php
while ($row = mysql_fetch_array($res)) {
if ($_GET['id']==$row["id"]) {
echo '<option selected="selected" value='.$row["id"].'>'.$row["name"].'</option>';
} else {
echo '<option value='.$row["id"].'>'.$row["name"].'</option>';
}
}
?>
</select>
Upvotes: 0
Reputation: 1500
Compare GET value with current loop value
<?php while ($row = mysql_fetch_array($res)) {echo '<option '.(($row['id'] == $_GET['id']) ? 'selected' : '').' value='.$row["id"].'>'.$row["name"].'</option>';}?>
Upvotes: 1