【问题标题】:PHP - Setting default year in selection boxPHP - 在选择框中设置默认年份
【发布时间】:2019-02-17 11:42:15
【问题描述】:

我是 PHP 新手。我有一个选择框,其年份范围从当年开始 - 5(2014 年)到 2050 年。我的选择框包含正确的年份,但我需要将其默认为当年。现在,它默认为 2014 年。我已经为此工作了几个小时。我认为循环中需要 $current_year 变量以某种方式 - 为了设置默认值 - 但这不起作用。在研究并看到各种示例之后,我现在认为我需要在循环中构建一个 if 语句,但我真的不知道。

<form id="calendarForm" name="calendarForm" method="post" action="">
    <label for="select_year">Select the year: </label>
    <select id="select_year" name="select_year">
        <?php
        $date = new DateTime();
        // Sets the current year
        $current_year = $date->format('Y');
        // Year to start available options.
        $earliest_year = ($current_year - 5);
        $year = $earliest_year;

        for ($year = $earliest_year; $year <= LATEST_YEAR; $year++) {
            echo "<option value='$year'>$year</option>";
        }
        ?>

    </select>

【问题讨论】:

  • 为什么在 ($current_year-5); 周围有括号?
  • 另外,我想知道 $year=$earliest_year 是否是多余的。
  • @RussJ 我想我需要括号。
  • 我认为那里没有必要。

标签: php


【解决方案1】:

如下修改你的 for 循环:

for ($year = $earliest_year; $year <= LATEST_YEAR; $year++) {
  if($year==$current_year)
        {
                echo "<option value='$year' selected>$year</option>";
        }
     else{
         echo "<option value='$year'>$year</option>";
        }
        }

【讨论】:

    【解决方案2】:

    试试下面的。您需要调整您的 php 标签,但要整洁。

    <option value='$year' <?php if($year == date("Y")) {echo "selected";}?> >$year</option>";
    

    它将检查当前年份,如果匹配,将成为选定的选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-25
      • 2021-04-26
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2017-12-11
      相关资源
      最近更新 更多