[英]How to set default choice in drop down list on first page load using PHP?
我使用以下代碼創建了一個下拉列表,但我想在頁面的第一次加載時設置默認選項(即,顯示最新日期,而不是第一組選項)。 我怎樣才能做到這一點?
<?php
$startyear = "";
$startmonth = "";
$startday = "";
$endyear = "";
$endmonth = "";
$endday = "";
$year = range(1998,2012);
$month = range(01,12);
$day = range(01,31);
if($_SERVER['REQUEST_METHOD']=='POST')
{
foreach($_POST as $key=>$value)
{
if(is_numeric($value))
{
$$key = $value;
}
}
}
?>
在這里填寫資料
<form name='update' action='' method='POST'>
Start: <select name='startyear'>
<?php foreach(array_reverse($year) as $y):?>
<option value="<?php echo $y?>"<?php echo((isset($startyear) && $startyear == $y)?' selected':null)?>><?php echo $y?></option>
<?php endforeach;?>
</select>
<select name='startmonth'>
<?php foreach($month as $m): $m = str_pad($m, 2, "0", STR_PAD_LEFT);?>
<option value="<?php echo $m;?>"<?php echo ((isset($startmonth) && $startmonth == $m)?' selected':null)?>><?php echo $m;?></option>
<?php endforeach;?>
</select>
<select name='startday'>
<?php foreach($day as $d): $d = str_pad($d, 2, "0", STR_PAD_LEFT);?>
<option value="<?php echo $d;?>"<?php echo ((isset($startday) && $startday == $d)?' selected':null)?>><?php echo $d;?></option>
<?php endforeach;?>
</select>
<input type='submit' value='View'/>
</form>
if($_SERVER['REQUEST_METHOD']=='POST')
{
...
} else {
// Set your defaults here.
}
由於您被選中的檢查是這樣完成的:
<?php echo ((isset($startday) && $startday == $d)?' selected':null)?>
只需使用默認值定義變量,它們為空!
$startyear = "";
$startmonth = "";
$startday = "";
$endyear = "";
$endmonth = "";
$endday = "";
這是你想要的嗎?
$cur_day = date('j');
$cur_mon = date('n');
$cur_year = date('Y');
然后在選項循環中像這樣
if($y == $cur_year) echo 'selected';
那么默認情況下將選擇當前年份,對月份和日期也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.