sleepingpeace Posted November 21, 2011 Share Posted November 21, 2011 If I have a variable and a hard coded select dropdown, what is the easiest way to compare the variable with the value and set that particular option's selected attributed to selected? Link to comment https://forums.phpfreaks.com/topic/251577-select-dropdowns-and-the-selected-option/ Share on other sites More sharing options...
Alexv Posted November 21, 2011 Share Posted November 21, 2011 Only way i can think of is by using JavaScript. Link to comment https://forums.phpfreaks.com/topic/251577-select-dropdowns-and-the-selected-option/#findComment-1290198 Share on other sites More sharing options...
Psycho Posted November 21, 2011 Share Posted November 21, 2011 If I have a variable and a hard coded select dropdown, what is the easiest way to compare the variable with the value and set that particular option's selected attributed to selected? You can start by making your drop-down to NOT be hard coded. At the very least make your options a hard-coded array, then build the select list dynamically so you can auto-select the appropriate value. Here is some rough sample code <?php $selectedValue = 'b'; $colorList = ( 'r' => 'Red', 'g' => 'Green', 'b' => 'Blue', 'y' => 'Yellow', 'p' => 'Purple' ) $colorOptions = ''; foreach($colorList as $value => $label) { $selected = ($selectedValue==$value) ? ' selected="selected"' : ''; $colorOptions .= "<option value='{$value}'>{$label}</option>\n"; } ?> Select a color: <select name="color"> <?php echo $colorOptions; ?> </select> Link to comment https://forums.phpfreaks.com/topic/251577-select-dropdowns-and-the-selected-option/#findComment-1290200 Share on other sites More sharing options...
sleepingpeace Posted November 21, 2011 Author Share Posted November 21, 2011 Excellent response and just what I needed. With a few adjustments to your rough draft it worked perfectly. Thank God for forums and intelligent people. Link to comment https://forums.phpfreaks.com/topic/251577-select-dropdowns-and-the-selected-option/#findComment-1290208 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.