简体   繁体   中英

HTML Dropdown Menu Previously Selected Value

I am using PHP and HTML to construct a HTML table that generates with a PHP while loop. I am populating a HTML dropdown menu with all of the distinct portfolio names in my mySQL database. To do this I am doing:

$query2 = "SELECT DISTINCT PORT FROM CELP";
$result2 = mysql_query($query2) or die (mysql_query($default));
if ($result2)
{
  {
echo "<select id='port' name='port'>";
while ($col = mysql_fetch_array($result2)) {
echo "<option value='" . $col[0] . "'>" . $col[0] . "</option";
}
echo "</select>";
} }

This works but whenever I submit my form the dropdown value I selected resets to the default first value. How can I put the "selected" tag in the option that was last submitted, and that one only. PS I use $_GET and the variable name for that is port, so it shows the currently selected portfolio in the URL.

Do this:

while ($col = mysql_fetch_array($result2)) {
    if(shouldBeSelected)
    {
       echo "<option selected="selected" value='" . $col[0] . "'>" . $col[0] . "</option";
    }
    else
    {
        echo "<option value='" . $col[0] . "'>" . $col[0] . "</option";
    }
}

Do it for the one that should be selected. You just need to use the selected property.

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