문제

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