views:

683

answers:

2

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

<select selected="<?php print($row[month]); ?>"><option value="Janurary">January</option><option value="February">February</option><option value="March">March</option><option value="April">April</option></select>

The database holds a month.. and i want to allow on the edit page, them to choose this month.. but it to be pre-filled with their current setting?

+2  A: 

You need to set the selected attribute of the correct option tag:

<option value="January" selected="selected">January</option>

Your PHP would look something like this:

<option value="January"<?=$row['month'] == 'January' ? ' selected="selected"' : '';?>>January</option>

I usually find it neater to create an array of values and loop through that to create a dropdown.

Greg
Erk sorry, didn't see your mostly identical comment before posting mine. I'll upvote yours but leave it to the questioner to pick a winner. Btw, does your opening PHP tag have a typo? or is `<?=` valid?
James Wheare
Yours gets the tick :) Makes more sense to me haha!
tarnfeld
<?= is valid - it does an echo for you
Greg
I had to modify this, had to put an if statement in.. didn't work otherwise :)
tarnfeld
+1  A: 

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.

James Wheare