Jump to content

[SOLVED] auto-setting a select drop-down


HaLo2FrEeEk

Recommended Posts

Hey, I have 3 select menus for dates, I need to be able to auto set (on load) which number in the dropdown is selected, for example, if the date I pass to the page is this:

 

01/15/2007

 

I would use explode("/", $date) to get each number, I know for a fact that the format will always be (month)/(day)/(year), so no worries with that, but then how would I make it so that January is selected automatically, as is 15th, and the year 2007, in the drop-down menus?

 

Thank you.

Link to comment
https://forums.phpfreaks.com/topic/65794-solved-auto-setting-a-select-drop-down/
Share on other sites

i can only think of this silly way:

 

<?php
// you get this from the 'explode'
$num = 5;
?>

<select id="s1">
<option value="1" <?php echo ($num == 1)?"selected":""; ?>>1</option>
<option value="2" <?php echo ($num == 2)?"selected":""; ?>>2</option>
<option value="3" <?php echo ($num == 3)?"selected":""; ?>>3</option>
<option value="4" <?php echo ($num == 4)?"selected":""; ?>>4</option>
<option value="5" <?php echo ($num == 5)?"selected":""; ?>>5</option>
<option value="6" <?php echo ($num == 6)?"selected":""; ?>>6</option>
<option value="7" <?php echo ($num == 7)?"selected":""; ?>>7</option>
<option value="8" <?php echo ($num == ?"selected":""; ?>>8</option>
<option value="9" <?php echo ($num == 9)?"selected":""; ?>>9</option>
</select>

Trivial example. You can expand and dress it up to suit.

 

<?php
list($m,$d,$y) = explode("/",$_GET['date']);

echo "Month: <select name='month'>\n";
for ($mo=1;$mo<13;$mo++) {
    echo "<option value='". $mo. "'";
    if ($mo==$m) { echo " selected='selected'";}
    echo ">". $mo. "</option>\n";
}
echo "</select>";
?>

Ok, well I messed around and figured out this (I decided to give up the date one, but I needed it for something else too):

 

echo "<select>";
$roles = array('Peon', 'Member', 'Staff', 'Overlord');
$role = "Member";
foreach($roles as $pos) {
  $sel = ($pos == $role) ? 'SELECTED' : '';
  echo "<option value=\"$pos\" $sel>$pos</option>\n";
  }
echo "</select>";

 

I'll see if I can do that with the date, somehow.  Thanks guys!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.