How do I set the selected item in a drop down box

2019-01-10 23:50发布

Is there any way to set the selected item in a drop down box using the following 'type' code?

<select selected="<?php print($row[month]); ?>"><option value="Janurary">January</option><option value="February">February</option><option value="March">March</option><option value="April">April</option></select>

The database holds a month.. and I want to allow on the edit page, them to choose this month.. but it to be pre-filled with their current setting?

9条回答
劳资没心,怎么记你
2楼-- · 2019-01-11 00:24

This is the solution that I came up with...

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">   
    <select name="select_month">
        <?php
            if (isset($_POST['select_month'])) {
                if($_POST["select_month"] == "January"){
                    echo '<option value="January" selected="selected">January</option><option value="February">February</option>';
                }
                elseif($_POST["select_month"] == "February"){
                    echo '<option value="January">January</option><option value="February" selected="selected">February</option>';
                }
            }
            else{
                echo '<option value="January">January</option><option value="February">February</option>';
            }
        ?>
    </select>
    <input name="submit_button" type="submit" value="Search Month">
</form>
查看更多
何必那么认真
3楼-- · 2019-01-11 00:28

You can try this after select tag:

<option value="yes" selected>yes</option>
<option value="no">no</option>
查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-11 00:33

You can use this method if you use a MySQL database:

include('sql_connect.php');
$result = mysql_query("SELECT * FROM users WHERE `id`!='".$user_id."'");
while ($row = mysql_fetch_array($result))
{
    if ($_GET['to'] == $row['id'])
    {
        $selected = 'selected="selected"';
    }
    else
    {
    $selected = '';
    }
    echo('<option value="'.$row['id'].' '.$selected.'">'.$row['username'].' ('.$row['fname'].' '.substr($row['lname'],0,1).'.)</option>');
}
mysql_close($con);

It will compare if the user in $_GET['to'] is the same as $row['id'] in table, if yes, the $selected will be created. This was for a private messaging system...

查看更多
登录 后发表回答