Alright so I have a website where people can create and edit profiles. One of the fields on their profile is state. All the info is stored as a row in a mysql database. When someone edits their profile they get a form with all their current information already filled in. However I can't figure out how to make the combo box have the persons current state selection selected as default. Does anyone know how to do this?
thanks,
james
combo box + database
Moderator: General Moderators
Code: Select all
<option name="state" value="MA" selected><option>How do you get it there? Well it depends on you PHP code.
Create the HTML of the combobox in a loop (Each time you move through the loop, you add something else to the combobox. You could just store all the options in an array and move through that array). Inside that loop, just check the value you're about to insert to see if it's the same as the user's current selection. If it's the same, add " selected='selected' " to the option.
You can use the following template I often find useful. It has some example data in it. As you can see the selected option needs to be the first placed into the selection. This data can come from a database source rather than manual entered as it is here.
This bit appears at the top of the selection:
Notice its called default.
Code: Select all
<?php
function mkSelect($name, $nopt, $options, $default) {
select name="".$name."\">\n";
list($defkey,$defval) = each($default);
$out .= "<option value=\"".$defkey."\" selected>".$defval."</option>\n";
while (list($key,$val) = each($options)) {
if ($key != $defkey)
$out .= "<option value=\"".$key."\">".$val."</option>\n";
}
$out .= "</select>\n";
return $out;
}
$name = 'testSelect';
$options[1] = 'chicken';
$options[2] = 'monkey';
$options[3] = 'cow';
$default[0] = 'null';
$htmlSelect = mkSelect($name,'', $options, $default);
?>Code: Select all
$out .= "<option value=\"".$defkey."\" selected>".$defval."</option>\n";