<?php
$options = '';
$valueFromDb = 1;
for($i = 1;$i<=4 ; $i++)
{
if( $i == $valueFromDb) {
$options .= '<option value="'.$i.'" selected="selected">'.$i.'Time</option>';
} else {
$options .= '<option value="'.$i.'" >'.$i.'Time</option>';
}
}
?>
<div class="form-group">
<label class="col-md-4 control-label" for="tidspunkt_varighed">V�lg Antal Timer</label>
<div class="col-md-4">
<select id="tidspunkt_varighed" name="tidspunkt_varighed" class="form-control">
<?php echo $options;?>
</select>
</div>
</div>
Pregunta
I have a problem, where I want to get a value from the database, and if the value matches the one in my option, the option should be selected.
This is my form:
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="tidspunkt_varighed">Vælg Antal Timer</label>
<div class="col-md-4">
<select id="tidspunkt_varighed" name="tidspunkt_varighed" class="form-control">
<option value="1">1 Time</option>
<option value="2">2 Timer</option>
<option value="3">3 Timer</option>
<option value="4">4 Timer</option>
</select>
</div>
</div>
I don't want to make an if clause every line.
Thanks in advance.
Kristian
Solución 2
Otros consejos
You should use a loop as your values are incremental when check with one if()
inside the loop for the checked value.
I think, you can use an array somehow like that:
<?
$value=YOUR_VALUE_FROM_DB
$selected[$value]="selected";
?>
<option value="1" <?=$selected[1]?>>1 Time</option>
<option value="2" <?=$selected[2]?>>2 Timer</option>
etc.
if you are not displaying these options using a loop then you have to put if with every option like
<option value="1" <?php if($dbvalue == 1){echo 'selected="selected"';}>1 Time</option>
and in case you are showing options using a loop you can put a condition in the loop and make a string like $selected = 'selected="selected"'; based on the condition, and echo $selected with every option.
$val_from_db = 3;
$output = '<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="tidspunkt_varighed">Vælg Antal Timer</label>
<div class="col-md-4">
<select id="tidspunkt_varighed" name="tidspunkt_varighed" class="form-control">';
foreach( $values as $key=>$value ) {
if ( $key==$val_from_db )
$selected = 'selected="selected" ';
else
$selected = '';
$output .= '<option '.$selected.'value="'.$key.'">'.$value.'</option>';
}
$output .= '</select>
</div>
</div>';
echo $output;