创建选择选项并获取月份和日期的当前值

时间:2013-08-31 13:07:09

标签: php html select options

<select name="year"><?=options(date('Y'),1900)?></select>
<select name="month"><?php echo date('m');?><?=options(1,12,'callback_month')?></select>
<select name="day"><?php echo date('d');?><?=options(1,31)?></select>  

PHP

function options($from,$to,$callback=false)
{
    $reverse=false;

    if($from>$to)
    {
        $tmp=$from;
        $from=$to;
        $to=$tmp;

        $reverse=true;
    }

    $return_string=array();
    for($i=$from;$i<=$to;$i++)
    {
        $return_string[]='<option value="'.$i.'">'.($callback?$callback($i):$i).'</option>';
    }
    if($reverse)
    {
        $return_string=array_reverse($return_string);
    }

    return join('',$return_string);
}

function callback_month($month)
{
    return date('m',mktime(0,0,0,$month,1));
}

我应该怎样做才能将相应下拉列表中的当前月份和日期作为起始值,就像多年(2013年)一样。

3 个答案:

答案 0 :(得分:2)

尝试以下内容:

type功能

添加了新的参数options()
<select name="year"><?=options('year' ,date('Y'),1900)?></select>
<select name="month"><?php echo date('m');?><?=options('month', 1,12,'callback_month')?></select>
<select name="day"><?php echo date('d');?><?=options('day', 1,31)?></select>  

<?php

function options($type, $from,$to,$callback=false)
{
    $reverse=false;

    switch ($type)
    {
        case "year":
            $current = date('Y');
            break;
        case "month":
            $current = date('m');
            break;
        case "day":
            $current = date('d');
            break;
    }

    if($from>$to)
    {
        $tmp=$from;
        $from=$to;
        $to=$tmp;

        $reverse=true;
    }

    $return_string=array();
    for($i=$from;$i<=$to;$i++)
    {
        $selected = ($i == $current ? " selected" : "");
        $return_string[]='<option value="'.$i.'" '.$selected.'>'.($callback?$callback($i):$i).'</option>';
    }
    if($reverse)
    {
        $return_string=array_reverse($return_string);
    }

    return join('',$return_string);
}

function callback_month($month)
{
    return date('m',mktime(0,0,0,$month,1));
}

?>

答案 1 :(得分:1)

只检索当前日期FIRST并使用for循环每年减去

答案 2 :(得分:1)

使用 selected 属性:

e.g。

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi" selected>Audi</option>
</select>

在这里小提琴:http://jsfiddle.net/dd3FU/

只需将其放入if statement

享受!