简体   繁体   中英

How to give selected value in dropdown list inside while loop

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>';}?>

比较GET值和当前回路值

<?php while ($row = mysql_fetch_array($res)) {echo '<option '.(($row['id'] == $_GET['id']) ? 'selected' : '').' value='.$row["id"].'>'.$row["name"].'</option>';}?>

Fetch selected value from GET request to compare with each id and put selected attribute in option tag to make it selected by default.

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM