0

I want the value of the dropdown menu to stay when form is submitted. However, this dropdown menu is created entirely by PHP rather than individual hand-typed values.

<?php
echo '<select name="month"><option>Month</option>';
for($i = 1; $i <= 12; $i++) {
$i = str_pad($i, 2, 0, STR_PAD_LEFT);
echo "<option value='$i'>$i</option>";
}
echo '</select>';

Is there a way to have the selected="selected" on the value the user selects?

I have a version for "years" too, and it has 100 values. So I'm looking for a way to do this without having to hand-type values.

2
  • BTW your SELECT will show Month,1,2,3,4,5,6,7,8,9,10,11,12. Not sure <options>Month</option> should be in there. Commented Oct 4, 2017 at 18:09
  • @Nic That is something that's sometimes done to give the user an indication of what they're selecting. Instead of having a label next to the field. Commented Oct 4, 2017 at 18:16

2 Answers 2

1

When you're looping through, check if the submitted value equals the current value. If it does, select it:

for($i = 1; $i <= 12; $i++) {
    $i = str_pad($i, 2, 0, STR_PAD_LEFT);
    if ($i == $_POST["month"]) {
        echo "<option value='$i' selected>$i</option>";
    } else {
        echo "<option value='$i'>$i</option>";
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly. Thanks!
0

What about ordinary check:

...
for(....) {
   printf("<option %s value='{$i}'>{$i}</option>", 
        ($i == $_POST['month']) ? 'selected' : '');
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.