0

下面我有一个下拉菜单,如果表单中存在验证错误,它将保留在下拉菜单中选择的选项的显示,否则如果表单没有错误,则下拉菜单将返回显示“请选择”选项:

  $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>'; 
4

1 回答 1

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;  
        }
    }
}

即使它没有经过测试,它应该让你开始。希望能帮助到你!

于 2012-12-09T09:34:44.527 回答