Hello am having a dropdown box like the below one,
function dropdown( $name, array $options, $selected=null )
{
/*** begin the select ***/
$dropdown = '<select name="'.$name.'" id="'.$name.'">'."
";
$selected = $selected;
/*** loop over the options ***/
foreach( $options as $key=>$option )
{
/*** assign a selected value ***/
$select = $selected==$key ? ' selected' : null;
/*** add each option to the dropdown ***/
$dropdown .= '<option value="'.$key.'"'.$select.'>'.$option.'</option>'."
";
}
/*** close the select ***/
$dropdown .= '</select>'."
";
/*** and return the completed dropdown ***/
return $dropdown;
}
?>
<form>
<?php
$name = 'my_dropdown';
$options = array( 'dingo', 'wombat', 'kangaroo' );
$selected = 1;
echo dropdown( $name, $options, $selected );
?>
</form>
after running this code, everything is showing correctly, but the selected option is incorrect by changing the value of selected.
The problem is, its showing like this <option value="1" selected="">wombat</option>
but actually it should show like this <option value="1" selected>wombat</option>
Kindly suggest me how to solve this issue
Some browsers use selected=true
, some just selected
. Using both is fine too.
So don't check it in Firebug or something, because that might be something else then what is the actual code. Try
$select = $selected==$key ? ' selected="true" selected' : "";
ps. you can leave out $selected = $selected;