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

后端 未结 11 777
误落风尘
误落风尘 2020-11-29 04:16

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


                        
    
提交评论

  • 2020-11-29 04:46

    Simple and easy to understand example by using ternary operators to set selected value in php

    <?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
    <select class="form-control" title="Choose Plan">
    <?php foreach ($plan as $id=> $value) { ?>
      <option value="<?php echo $id;?>" <?php echo ($id==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
    <?php } ?>
    </select>
    
    0 讨论(0)
  • 2020-11-29 04:50

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

    0 讨论(0)
  • 2020-11-29 04:52

    You can try this after select tag:

    <option value="yes" selected>yes</option>
    <option value="no">no</option>
    
    0 讨论(0)
  • 2020-11-29 04:55

    You mark the selected item on the <option> tag, not the <select> tag.

    So your code should read something like this:

    <select>
        <option value="January"<?php if ($row[month] == 'January') echo ' selected="selected"'; ?>>January</option>
        <option value="February"<?php if ($row[month] == 'February') echo ' selected="selected"'; ?>>February</option>
        ...
        ...
        <option value="December"<?php if ($row[month] == 'December') echo ' selected="selected"'; ?>>December</option>
    </select>
    

    You can make this less repetitive by putting all the month names in an array and using a basic foreach over them.

    0 讨论(0)
  • 提交回复
    热议问题