2012-12-08 182 views
0

我不太得到下面右邊的代碼,但我有一個下拉菜單下面,我想它下面顯示這些值:如何顯示在下拉正確的選項下拉菜單並保留選項顯示

1 
1/2 
2 
2/3 
3 
3/4 
4 
4/5 

... 

10 

現在,我也希望能夠保持後所選擇的選項進行提交,我已經嘗試了下面這段代碼,但問題是,它是唯一的顯示值1/2, 2/3, 3/4, 4/5...

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

的origanl代碼是下面這樣的地方顯示正確的選項,但沒有執行$ validS ubmission變量,以便它不保存提交頁面後選擇了該選項:

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) { 
     if ($validSubmission && $year == $getduration) { 
      $durationHTML .= "<option value='" . $year . "' selected='selected'>$year</option>" . PHP_EOL; 
     } else { 
      $durationHTML .= "<option value='" . $year . "'>$year</option>" . PHP_EOL; 
     } 
    } 

但試圖結合這兩個代碼沒有奏效,那就是我的問題

回答

0

試試這個修改/簡化的代碼。通過使用ternary comparison-$var = condition ? if_true : if_false-設置selected='selected'屬性,可以最小化代碼(從~17行到~9)。

foreach ($years as $year) { 

    //Gets the single years - 1,2,3... 
    $sel =($validSubmission && $year == $getduration)? " selected='selected'": ""; 
    $durationHTML .= "<option value='$year'$sel>$year</option>".PHP_EOL; 

    //Gets the double years - 1/2,2/3,3/4... 
    if ($year != $max_year) { 
    $nextYear = $year + 1; 
    $sel =($validSubmission && ($year.'/'.$nextYear) == $getduration)? " selected='selected'": ""; 
    $durationHTML .= "<option value='$year/$nextYear'$sel>$year/$nextYear</option>".PHP_EOL; 
    } 
}