如何使用PHP在第一页加载的下拉列表中设置默认选项?

时间:2012-07-11 18:45:03

标签: php default drop-down-menu

我使用以下代码创建了一个下拉列表,但我想在页面的第一次加载时设置默认选项(即显示最近的日期,而不是第一组选项)。我怎么能这样做?

<?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>

3 个答案:

答案 0 :(得分:2)

if($_SERVER['REQUEST_METHOD']=='POST')
{
    ...
} else {
    // Set your defaults here.
}

答案 1 :(得分:1)

由于您选择的检查是这样完成的:

<?php echo ((isset($startday) && $startday == $d)?' selected':null)?>

只需使用默认值定义变量,它们就是空的!

$startyear = ""; 
$startmonth = "";
$startday = "";
$endyear = "";
$endmonth = "";
$endday = "";

答案 2 :(得分:0)

这是你想要的吗?

$cur_day  = date('j');
$cur_mon  = date('n');
$cur_year = date('Y');

然后在选项循环内部这样的

if($y == $cur_year) echo 'selected';

然后默认选择当前年份,每月和每天都这样做。