Dynamically loading select

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
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Dynamically loading select

Post by GeXus »

When dynamically populating a select box, how would you throw in a selected value? Basically I'm adding data and posting to the same page.. but I would like to have everything populated and selected on return...

Thanks!
User avatar
Nathaniel
Forum Contributor
Posts: 396
Joined: Wed Aug 31, 2005 5:58 pm
Location: Arkansas, USA

Post by Nathaniel »

The two methods I know of:

1) Add <?PHP if ( $option == 'this_option_value' ): ?>checked="checked"<?PHP endif; ?> in every option tag. For example,

Code: Select all

<option value="this_option_value" <?PHP if ( $option == 'this_option_value' ): ?>checked="checked"<?PHP endif; ?>>This Option Value</option>
2) Output buffer the select box, and

Code: Select all

str_replace($option, $option . ' checked="checked"', $buffered_output);
where $option equals the value of the option.
Post Reply