简体   繁体   中英

How to sort a select option according to user input

Please I don't have any idea on how to achieve this so I need help. I have this code:

<select>
    <option>Sunday</option>
    <option>Monday</option>
    /* this option goes down to Saturday */
</select>

And the user have to choose an option which is inserted into the database, let's assume the user chooses Tuesday and wants to edit it later on. Now I want the option that will be visible to be Tuesday eg:

<select>
    <option>Sunday</option>
    <option>Monday</option>
   <option>Tuesday</option> /* this option will be the visible option before the user opens the selection */
</select>

And I want to achieve this through PHP and the variable assigned to the outputted database info is $day so $day = 'Tuesday'; please how do I achieve this?

To do this from within PHP you could do

<select>
    <option <?PHP echo $day=='Sunday' ? '"selected=selected"' : ''); ?>>Sunday</option> 
    <option <?PHP echo $day=='Monday' ? '"selected=selected"' : ''); ?>>Monday</option> 
    <option <?PHP echo $day=='Tuesday' ? '"selected=selected"' : ''); ?>>Tuesday</option> 

...

</select>

But it is not very elegant and gets difficult to code and more importantly maintain if the selection were to contain more that the seven days of the week.

So using an array of day names and a foreach loop and your $day variable containing the user selected day.

<?php
$dow = array('Sunday','Monday','Tuesday','Wednesday',
             'Thursday','Friday','Saturday');
?>
<select name="DayOfWeek">

<?php
    foreach ( $dow as $d ) :
        $sel = $d == $day ? 'selected="selected"' : '';
        echo "<option $sel>$d</option>";
    endforeach;
?>
</select>

You can try this is example and you can apply for all of select options

<select>
   <option <?PHP echo ($day=='Tuesday' ? selected : ""); ?>>Tuesday</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