Jump to content

Select DropDowns And The Selected Option


sleepingpeace

Recommended Posts

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>

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.