default value of dropdown on webpage

时光怂恿深爱的人放手 提交于 2020-01-17 02:48:09

问题


This may be complicated to explain. I have set up a timesheet system where employees can insert into a mysql db their own timesheet records. this works fine but i've given them the option to edit an item they have inserted, so what i have is a dropdown displaying from mysql all project numbers available for them to pick but i also want to set the default value of the dropdown to the project number which they selected when they inserted the record (ie. to avoid having to remember what project it was)

here is my code:

$result1 = mysql_query("select project_no from `projects`") or die(mysql_error());
            echo '<select name="project" class="project">';
        while($row1 = mysql_fetch_array($result1)){
            echo "<option selected='yes' value=".$row1['project_no'].">".$row1['project_no']."</option>";
        }
            echo '</select>';

The record is stored in a table called timesheets, so i can do a SELECT from that but i'm not sure how to set the right project number as the default value in the above dropdown?

Does that make sense?


回答1:


Store the project number in a variable, e.g., $projnum, and compare it with each value.

$result1 = mysql_query("select project_no from `projects`") or die(mysql_error());
            echo '<select name="project" class="project">';
        while($row1 = mysql_fetch_array($result1)){
            echo "<option ";
            if ($row1['project_no'] == $projnum) { echo 'selected="selected"; }
            echo " value=".$row1['project_no'].">".$row1['project_no']."</option>";
        }
            echo '</select>';



回答2:


    $project_to_select = 42;

    while($row1 = mysql_fetch_array($result1)){
        echo "<option " . ($row1['project_no'] == $project_to_select ? "selected='selected'" : "") . " value=".$row1['project_no'].">".$row1['project_no']."</option>";
    }



回答3:


Change

selected='yes'

To

selected='selected'


来源:https://stackoverflow.com/questions/4625373/default-value-of-dropdown-on-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!