Hongxuan
Hongxuan

Reputation: 117

select option: display current date at first time, display last selected date in future

I am a IT newbie and i am really confused with this stupid (look like?) question.. I want to have a select list, it appears current date by default. But after I submit the page (form) and returns error, the select list will show the last submitted date.

Here is my php code for month option:

function MonthOptions()
{
    $months = array( "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" );
    for($i=1; $i<=12;$i++)
    {


        if($i==date("m"))
            print '<option value="'.$i.'" selected>'.$months[$i-1].'</option>';
        if($i==$this->form['months'])
            print '<option value="'.$i.'" selected>'.$months[$i-1].'</option>';
        else
            print '<option value="'.$i.'" >'.$months[$i-1].'</option>';

    }
}

and my html:

<select name="months" class="date_option">
            <?php $this->MonthOptions() ?>
</select>

Now the problem is very weird, if i submit the month(day, or year) after today's month(day, or year), my function works correctly. But if i select the month(day, or year) before current date, after i submit the page, the select option shows the current month(day, or year)..

Upvotes: 1

Views: 1732

Answers (1)

Malitta N
Malitta N

Reputation: 3423

Change the list of arguments and make the second if condition an else if. The meaning of the second condition is, the current month should be only selected if the month has not already being submitted.

if($i==$this->form['months']) {
     print '<option value="'.$i.'" selected>'.$months[$i-1].'</option>';
} else if ($i==date("m")  && @empty($this->form['months'])) {
     print '<option value="'.$i.'" selected>'.$months[$i-1].'</option>';
} else {
     print '<option value="'.$i.'" >'.$months[$i-1].'</option>';
}

Upvotes: 0

Related Questions