I have a form where the user inserts and selects some data in a form, one of the select fields is his/her birth year.
The drop-down list is populated fine, BUT after submitting the form for validation, I can not preserve the selected year and the user has to re-select it again!
This is what I've done:
<select size="1" name="birthYear" tabindex="7">
// Please Select Option
<option selected value="-1" <?php if(isset($_POST['birthYear']) && $_POST['birthYear'] == '-1') { echo 'selected="selected"'; } ?> >Please Select</option>
// populate birth years range
<?php
$currentYear = date('Y');
$minimumBirthYear = $currentYear - 10;
$MaximumBirthYear = $currentYear - 100;
for($i = $minimumBirthYear; $i >= $MaximumBirthYear; $i--){
echo '<option value="'.$i.'">'.$i.'</option><br />';
}
?>
</select>
Can you please help me in applying the
<?php if(isset($_POST['birthYear']) && $_POST['birthYear'] == '-1') { echo 'selected="selected"'; } ?> >
in the for loop? I've tried it in different ways but with no luck!
Thanks in advance...
Try this:
for($i = $minimumBirthYear; $i >= $MaximumBirthYear; $i--){
echo '<option '.(isset($_POST['birthYear']) && $_POST['birthYear'] == $i ? 'selected' : '').' value="'.$i.'">'.$i.'</option><br />';
}
<select size="1" name="birthYear" tabindex="7">
// Please Select Option
<option selected value="-1">Please Select</option>
// populate birth years range
<?php
$currentYear = date('Y');
$minimumBirthYear = $currentYear - 10;
$MaximumBirthYear = $currentYear - 100;
for($i = $minimumBirthYear; $i >= $MaximumBirthYear; $i--)
{
echo sprintf("<option value='%s' %s >%s</option><br/>", $i, isset($_POST['birthYear']) && $_POST['birthYear']? "selected='selected'": "", $i);
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.