Pre-filling select tags from array
I've g开发者_如何学Cot this array:
$profession_type = array(
'Professional Engineers',
'Accountants',
'Insurance Professionals',
'Attorneys',
'Certified Hazardous Materials Managers',
'Safety Professional',
'Industrial Hygienists',
'IT Professionals',
'Human Resource'
);
I am display the contents of the array as the options for the select tag:
<select name="profession_type[]">
<option value=""></option>
EOL;
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
print <<<EOL
</select>
I've never pre-filled a drop down box with dynamic values. The values in $profession_type
will change frequently (and will eventually be driven from a table in the db), so I can't do hard code it.
EDIT: Sorry my question was unclear.
- The user will select a value from a previous screen (say it's called id) and hit submit.
- Before the HTML is rendered to the screen, PHP makes a stored procedure call based on the
id
they selected. - The values that the stored procedures returns will prefill the "profession_type[]" form field.
- I would like the
<option value='accountants' selected>Accountants</option>
if the stored procedure returns "Accountants" for the value of "profession_type" based on the id.
Is that more clear? Sorry.
Any suggestions?
How about this:
print '<select name="profession_type">';
print '<option value=""></option>';
foreach ($profession_type as $p)
{
if ($p == $chosen_profession)
print "<option value='" . $p . "' selected='selected'>" . $p . "</option>";
else
print "<option value='" . $p . "'>" . $p . "</option>";
}
print '</select>';
This goes in your .php file:
<!-- some HTML here -->
<?php
$profession_type = [result_from_database_query] ?>
<!-- more HTML here -->
<select name="profession_type">
<?php
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
?>
</select>
精彩评论