Reputation: 2188
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?
Upvotes: 1
Views: 137
Reputation: 2055
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>
Upvotes: 1
Reputation: 94672
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>
Upvotes: 3