[英]How to display correct options in drop down menu AND keep option displayed
[英]How to state whether option is selected and display correct values in drop down menu
在下方,我有一個下拉菜單,如果表單中存在驗證錯誤,它將保持下拉菜單中所選選項的顯示,否則,如果表單沒有錯誤,則下拉菜單將返回顯示“請選擇“選項:
$validSubmission = isset($_POST['registerbtn']) isset($getyear);
$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$yearHTML = '';
$yearHTML .= '<select name="year" id="yearDrop">'.PHP_EOL;
$yearHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($years as $year) {
if ($validSubmission && $year == $_POST['year'] && $numrows != 1) {
$yearHTML .= "<option value='" . $year . "' selected='selected'>$year</option>" . PHP_EOL;
} else {
$yearHTML .= "<option value='" . $year . "'>$year</option>" . PHP_EOL;
}
}
$yearHTML .= '</select>';
上述下拉列表的值為:
1
2
3
4
5
...
10
但是我在下面的下拉菜單中使用相同的方法時遇到問題,因為下拉菜單包含兩種類型的選項,其中包含一個年份的單個數字,以及那些顯示一年中多個值且之間帶有/的選項:
1
1/2
2
2/3
3
3/4
4
4/5
5
....
10
我的問題是,如果表單中有錯誤,如何將上面的格式用於下面的下拉菜單代碼,以便使選定的選項保持選中狀態;否則,如果表單沒有錯誤,則返回顯示“請選擇”值在下拉菜單中?
$validSubmission = (isset($_POST['createbtn']) && isset($getcourseid) && isset($getcoursename) && isset($getduration));
$durationHTML = '';
$durationHTML .= '<select name="duration" id="durationDrop">'.PHP_EOL;
$durationHTML .= '<option value="">Please Select</option>'.PHP_EOL;
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>';
嘗試這樣:
foreach ($years as $year)
{
$nextYear = $year + 1;
//check for the "simple years"
if ($validSubmission && $year == $_POST['duration'])
{
$durationHTML .= "<option selected>$year</option>".PHP_EOL;
}
else
{
$durationHTML .= "<option>$year</option>".PHP_EOL;
}
//check for the timespans
if ($year != $max_year)
{
$nextYear = $year + 1;
if ($validSubmission && ($year . "/" . $nextYear) == $_POST['duration'])
{
$durationHTML .= "<option selected>$year/$nextYear</option>".PHP_EOL;
}
else
{
$durationHTML .= "<option>$year/$nextYear</option>".PHP_EOL;
}
}
}
即使未經測試,它也可以幫助您入門。 希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.