Question

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

What should i make to get the current month and date in the corresponding dropdowns as starting values, as it is the case with years (2013).

Was it helpful?

Solution

Try like following:

Added new param type to options() function

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

?>

OTHER TIPS

just retreive the current date FIRST and use a for loop to subtract each year

Use selected Attribute:

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>

Fiddle here: http://jsfiddle.net/dd3FU/

Just put it inside an if statement.

Enjoy!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top