define initially selected option

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lcky13
Forum Newbie
Posts: 8
Joined: Sat Nov 26, 2005 9:28 pm

define initially selected option

Post by lcky13 »

In php is there any way to define what is selected when the user enters the page. For example, I have a drop down list of months. I would like November to be the initially selected option. Can this be done with PHP?
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

done with HTML that is.

use something like this you should:

Code: Select all

<select name="month">
<option value="January">Januray</option>
..
<option value="November" selected="selected">November</option>
</select>
make that dynamic with php you could (to select the current month etc). But output to the client in HTML it must.
lcky13
Forum Newbie
Posts: 8
Joined: Sat Nov 26, 2005 9:28 pm

Post by lcky13 »

that is what I need to do, make it dynamic?
how do I accomplish this with php?
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

untested this is...

Code: Select all

$mon = date("F");
echo "<select name=\"month\">";
echo "<option value=\"January\" ".($mon == "January" ? "selected=\"selected\"" : "").">January</option>";
echo "</select>";
lcky13
Forum Newbie
Posts: 8
Joined: Sat Nov 26, 2005 9:28 pm

Post by lcky13 »

<?php if($m == "January"){echo " selected";}?>

ended up just inserting this into my html

works!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

$months = array(
   'January',
   'Febuary',
   'March',
   'April',
   'May',
   'June',
   'July',
   'August',
   'September',
   'November',
   'December',
);

echo '<select name="month">';

foreach ($months as $month) {
   echo '<option value="'.$month.'" '.($month == date('F', time()) ? 'selected="selected"' : '').'>'.$month.'</option>';
} 

echo '</select>';
Post Reply