質問

I have this form:

<form method="post">
<fieldset>
    <select name="taskOption" required>
    <option value="" disabled selected>Choose group</option>

    <?php

    while($hej < count($hejsan)) {
        echo '<option value=' . $hej . '>' . $hejsan[$hej] . '</option>';
        $hej++;
    }

    ?>

    </select>


    <input type="submit" value="Find bookings">
</fieldset>
</form>

When I press the submit button the select/option will reset to the default, how can I change this and make it stay as the one I selected?

役に立ちましたか?

解決

Try this

 if (isset($_POST['taskOption'])) {
    $Option = $_POST['taskOption'];
   }
while($hej < count($hejsan)) {
        if($hej==$_POST['taskOption']){
           $selected = "selected=selected";
         }else{
           $selected = "";
         }
    echo '<option value="' . $hej . '" '.$selected .'>' . $hejsan[$hej] . '</option>';
    $hej++;
}

他のヒント

You will need to look at the option you have selected and make the corresponding option selected. Since your form leads to the same page, you can just look at the contents of $_POST.

P.S.: also, you will find it useful to echo a newline after each option to make the output more readable.

Try this:

<?php
$taskOption = '';
if (isset($_POST['taskOption']) {
  $taskOption = $_POST['taskOption'];
}
?>
<form method="post">
<fieldset>
    <select name="taskOption" required>
    <option value="" disabled selected>Choose group</option>

    <?php

    while($hej < count($hejsan)) {
        if ($hey == $taskOption) {
            echo "<option value={$hey} selected>{$hejsan[$hej]}</option>";
        } else {
            echo "<option value={$hey}>{$hejsan[$hej]}</option>";
        }
        $hej++;
    }

    ?>

    </select>


    <input type="submit" value="Find bookings">
</fieldset>
</form>

At a if else statement to it. If the option value is equal to the select, then add the selected="selected"

This is an example code. could be that the operator is wrong, im always confused with the greater then and smaller then operators.

<?php

$option_value = 5;

for($i=0; $i > 10; $i++){
    if($option_value == 5){
        echo '<option value="'.$i.'" selected="selected">Item number'.$i.' is selected</option>';
    } else {
        echo '<option value="'.$i.'">Item number'.$i.'</option>';
    }
}


?>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top