记住选择字段值

时间:2014-04-11 06:58:04

标签: php html5

public static function load_months()
{
    $output = "\n <select id='month' name='month'>";
    $output .= "\n <option value='0'>Month</option>";

    for($i = 1 ; $i <= 12; $i++)
    {
        $timestamp = mktime(0, 0, 0, $i, 10, 1980);
        $monthName = date("F", $timestamp);
        $output .= "\n <option value='$i'>$monthName</option>";
    }

    $output .= "\n </select>";
    echo($output);
}

我已经在上面的代码中显示了选择月份名称。我想让这个脚本记住发布的选定选项,就像我在会话数组下面的名字字段一样。怎么做?

<input type="text" name="fname" value="<?= $user_data->first_name ?>" placeholder="First Name" required>

3 个答案:

答案 0 :(得分:2)

您想要使用&#34;选择&#34;选项元素的属性。

public static function load_months($user_data = null)
{
    $output = "\n <select id='month' name='month'>";
    $output .= "\n <option value='0'>Month</option>";

    for($i = 1 ; $i <= 12; $i++)
    {
        $selected = ( !is_null($user_data) && isset($user_data->month) && $user_data->month == $i ? 'selected="selected"' : '' );
        $timestamp = mktime(0, 0, 0, $i, 10, 1980);
        $monthName = date("F", $timestamp);
        $output .= sprintf("\n <option value='%s' %s>%s</option>",$i,$selected,$monthName);
    }

    $output .= "\n </select>";
    echo($output);
}

然而,如果您关注可扩展性。你可以做这样的事情

public static function load_months($selectedMonth = null)
{

    $output = "\n <select id='month' name='month'>";
    $output .= "\n <option value='0'>Month</option>";

    for($i = 1 ; $i <= 12; $i++)
    {
        $selected = ( !is_null($selectedMonth) && is_numeric($selectedMonth) && $selectedMonth == $i ? 'selected="selected"' : '' );
        $timestamp = mktime(0, 0, 0, $i, 10, 1980);
        $monthName = date("F", $timestamp);
        $output .= sprintf("\n <option value='%s' %s>%s</option>",$i,$selected,$monthName);
    }

    $output .= "\n </select>";
    echo($output);
}

您只需将选定的月份传递给方法。

答案 1 :(得分:0)

将所选值作为参数传递给函数 -

public static function load_months($selected)
{
    $output = "\n <select id='month' name='month'>";
    $output .= "\n <option value='0'>Month</option>";

    for($i = 1 ; $i <= 12; $i++)
    {
        $timestamp = mktime(0, 0, 0, $i, 10, 1980);
        $monthName = date("F", $timestamp);
         if($i==$selected)
      {
        $output .= "\n <option value='$i' selected='selected'>$monthName</option>";
      }
       else
      {
           $output .= "\n <option value='$i'>$monthName</option>";
       }
    }

    $output .= "\n </select>";
    echo($output);
}

答案 2 :(得分:0)

像这样:

if (isset($user_data->month) && $user_data->month == $i) {
            $output .= "\n <option selected='selected' value='$i'>$monthName</option>";
} else {
            $output .= "\n <option value='$i'>$monthName</option>";
}