Reputation: 1594
I have a php variable $valuable='bottomValue'
and a select drop down inside a form which upon submit returns to the same page
<form action='' method='post'>
<select>
<option value='topValue'>One</option>
<option value='midValue'>Two</option>
<option value='bottomValue'>Three</option>
</select>
<input name='theSubmit' type='submit' />
</form>
Based upon the value of the $valuable
how can I change the selected option to match.
For example on page load because the default value of the variable = 'bottomValue' option three would be selected
Upvotes: 1
Views: 8895
Reputation: 270
$valueable = 'bottomValue';
// array of the options you want to display in your select dropdown
$options = array(
'topValue' => 'One',
'midValue' => 'Two',
'bottomValue' => 'Three'
);
$html = '<form action='' method='post'>';
$html .= '<select>';
foreach($options as $value => $display){
if($value == $valuable){
$html .= '<option value="'.$value.'" selected>'.$display.'</option>';
}else{
$html .= '<option value="'.$value.'">'.$display.'</option>';
}
}
$html .= '</select>';
$html .= '<input name="theSubmit" type="submit" />';
$html .= '</form>';
echo $html;
Upvotes: 0
Reputation: 81
If you don't want to use other technology, javascript for example, you have to check the value for each option like this:
<option value='bottomValue' <?php echo ($valuable == 'bottomValue')?'selected':''; ?>>Three</option>
Upvotes: 1
Reputation: 651
first make Array of your values and then do this
$values = array (
1 => 'topValue',
2 => 'middleValue',
3=> 'bottomValue',
);
and then
<form action='' method='post'>
<select>
foreach( $values as $name => $v)
{
if( $name == $valuable )
{
echo '<option'.' value="'.$v.'"'.' selected="selected"'.'>'.$v.'</option>';
}
else
{
echo '<option'.' value="'.$v.'"'.'>'.$v.'</option>';
}
}
</select>
best thing abt this Method You dun need inline php code for eacchhh option:)
Upvotes: 0
Reputation: 439
You need to do smth like this:
<form action='' method='post'>
<select>
<option value='topValue'>One</option>
<option value='midValue'>Two</option>
<option value='bottomValue'
<?php echo $valuable == 'bottomValue' ? 'selected' : '' ?>
>Three</option>
</select>
<input name='theSubmit' type='submit' />
</form>
Upvotes: 0