下面我有一个下拉菜单,如果表单中有验证错误,它将保持在下拉菜单中选择的选项的显示,否则如果表单没有错误,则下拉菜单将返回到显示“请选择”选项:
$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>';
答案 0 :(得分:1)
尝试这样:
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;
}
}
}
即使没有经过测试,也应该让你开始。希望它有所帮助!