I am not quite getting the code below right but I have a drop down menu below where I want it to display these values below:
1
1/2
2
2/3
3
3/4
4
4/5
...
10
Now I also want to be able to keep the option selected after a submit so I have tried this code below but the problem is that it is only display values 1/2, 2/3, 3/4, 4/5... etc.
foreach ($years as $year) {
if ($validSubmission && $year == $getduration) {
if ($year != $max_year) {
$nextYear = $year + 1;
$durationHTML .= "<option value='" . $year . "' selected='selected'>$year/$nextYear</option>".PHP_EOL;
}else{
$durationHTML .= "<option value='" . $year . "' selected='selected'>$year</option>".PHP_EOL;
}
}else{
if ($year != $max_year) {
$nextYear = $year + 1;
$durationHTML .= "<option value='" . $year . "'>$year/$nextYear</option>".PHP_EOL;
}else{
$durationHTML .= "<option value='" . $year . "'>$year</option>" . PHP_EOL;
}
}
}
The origanl code was this below where it displays the correct options but did not perform the $validSubmission variable so that it does not keep the option selected after submitting a page:
foreach ($years as $year) {
$durationHTML .= "<option>$year</option>".PHP_EOL;
if ($year != $max_year) {
$nextYear = $year + 1;
$durationHTML .= "<option>$year/$nextYear</option>".PHP_EOL;
}
}
$durationHTML .= '</select>';
The code below does keep the option displayed after submit but does not display the values with / in between the values:
foreach ($years as $year) {
if ($validSubmission && $year == $getduration) {
$durationHTML .= "<option value='" . $year . "' selected='selected'>$year</option>" . PHP_EOL;
} else {
$durationHTML .= "<option value='" . $year . "'>$year</option>" . PHP_EOL;
}
}
But trying to combine both the code has not worked and that is the problem I am having
Try this modified/simplified code. By using a ternary comparison –
$var = condition ? if_true : if_false– to set theselected='selected'attribute, you can minimize the code (from ~17 lines to ~9).