Elon Gielink Elon Gielink - 7 months ago 14
PHP Question

Option value selected for loop

I am trying to create a

selected
value of the previous output.
(the user fills in a form , submits, returns to the form) And I want the selected value to be the value the user previously used.

The
vraagNummer
and
answer
are given in the url parameter and the dropdown menu of items available in the list are created in a for loop.
Now I got stuck on that part.. How do I create an option selected value if it is created in a for loop?

Usually I would just put in
option value = $vraagNummer selected> <?php echo $vraagNummer ?></option
but in this case that wouldn't work. I suppose?

Anyone knows how to fix this?

Same with the A/B/C/D. How do I put in the selected value of
answer
into the value previously selected while still keeping the others as an option.


With kind regards,

if(!empty($_GET['vraagnummer'])){
$vraagNummer = $_GET['vraagnummer'];
if(!empty($_GET['answer'])){
$answer = $_GET['answer'];
}
}
echo $vraagNummer;
echo $answer;
?>

<form id="start" method="post" action="index.php?test=true">
<select name="question">
<?php
for($i= 1; $i < $nRows+1 ; $i++){
?><option value="<?php echo $i ?>">Question <?php echo $i?></option>
<?php
}
?>
</select>
<select name="result">
<option value="A">Answer A</option>
<option value="B">Answer B</option>
<option value="C">Answer C</option>
<option value="D">Answer D</option>

<input type="submit" id="submit" value="Submit" />
</form>

Answer

You simply test the $_GET['question'] against the current $i value in the loop using a ternary if

<form id="start" method="post" action="index.php?test=true">
    <select name="question">
<?php 
    for($i= 1; $i < $nRows+1 ; $i++){
        $sel = (isset($_GET['question']) && $_GET['question'] == $i) ? 'selected="selected"' : '';
        echo '<option ' . $sel . ' value="' . $i .">Question ' . $i . '</option>';
    }
?>
    </select>

Warning:

Also be careful with the use of empty() when the variables can contain a zero as zero is considered as empty by the empty() function

Actually I would do your other dropdown like this

<select name="result">
foreach (range('A', 'D') as $char) {
    $sel = (isset($_GET['result']) && $char == $_GET['result']) ? 'selected="selected"' : '';
    echo "<option $sel value='$char'>Answer $char</option>\n";
}
</select>
Comments