How to echo out drop-down box selection?

Hi All,

I’m trying to echo out a value that was inserted into my database with a drop down box.

For example, when I click ‘edit’ for a row, I want that value to be the value pre-selected in the edit form drop-down box. However, it defaults to the first option in the ‘select’ tag on my edit form.

My question:
How do I do I accomplish this? I give my current code below which is not able to do this function. Thanks!

<select name="dropdown" value="<?php htmlout($value); ?>" />
<option>1</option>
<option>2</option>
<option>3</option>
</select>

The value= needs to go on each optiion - it isn’t valid on the select.

You need to set selected on the option that you want selected.

<select name="dropdown" />
<option<?php if ('1'==htmlout($value)) echo ' selected="selected"'?>>1</option>
<option<?php if ('2'==htmlout($value)) echo ' selected="selected"'?>>2</option>
<option<?php if ('3'==htmlout($value)) echo ' selected="selected"'?>>3</option>
</select>

Thanks, Felgall -

Unfortunately, I’m not able to make this work. When I use this code my dropdown box becomes empty.

Here is the code I’m using. Am I doing something wrong here?

<select name="type"/>
				<option<?php if ('Article'==htmlout($type))echo ' selected="selected"'?>>Article</option>
				<option<?php if ('Preface'==htmlout($type)) echo ' selected="selected"'?>>Preface</option>
				<option<?php if ('Review'==htmlout($type)) echo ' selected="selected"'?>>Review</option>
		</select>

Seems I’m following your code. If I code ’ <option <?php if…>> ’ then the drop down is populated but it does not echo back the chosen option.

Thanks for your help. BTW, I’m using Firefox, if that matters.

Thanks!


$types = array('Article','Preface','Review');
$type = isset($_POST['type']) && in_array($_POST['type'],$types)?$_POST['type']:'Article';

echo '<select name="type">';
foreach($types as $option) {
     echo '<option value="'.$option.'"'.(strcmp($option,$type)==0?' selected="selected"':'').'>'.$option.'</option>';
}
echo '</select>';

Thanks, oddz!

The code worked and it functions great.

I should say that I removed the line that defines “$type” since I already had that in my controller - took me a bit to realize this since it wasn’t working at first.

But, using my controller definition and removing that line it works great!

Cheers :cool: