萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 出生日期年月日三級聯動下拉選單完整實作 (含閏年判斷、ASP.NET 整合)

核心邏輯:每月天數與閏年規則

  • 大月 (31天):1、3、5、7、8、10、12 月
  • 小月 (30天):4、6、9、11 月
  • 2月:平年 28 天、閏年 29 天
  • 閏年規則:(year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)

完整前端實作 (原生 JS,無依賴)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>生日選擇器</title>
    <style>
        .selector-group { display:flex; gap:8px; align-items:center; font-family:sans-serif; }
        select { padding:6px 10px; border:1px solid #ccc; border-radius:4px; background:white; }
        label { font-size:14px; color:#666; }
    </style>
</head>
<body>
    <div class="selector-group">
        <label>出生日期:</label>
        <select id="selYear" onchange="updateDays()"><option value="">年</option></select>
        <select id="selMonth" onchange="updateDays()"><option value="">月</option></select>
        <select id="selDay"><option value="">日</option></select>
    </div>
    <input type="hidden" id="hidBirthDate" name="birthDate">
    <button type="button" onclick="saveDate()">儲存</button>

    <script>
        var MON_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        var $year = document.getElementById('selYear');
        var $month = document.getElementById('selMonth');
        var $day = document.getElementById('selDay');
        var $hidden = document.getElementById('hidBirthDate');

        // 初始化
        function init() {
            var now = new Date();
            var curYear = now.getFullYear();
            var curMonth = now.getMonth() + 1; // 1-12
            var curDay = now.getDate();

            // 年份:往前 80 年 ~ 明年
            for (var y = curYear - 80; y <= curYear + 1; y++) {
                $year.add(new Option(y + ' 年', y));
            }
            $year.value = curYear;

            // 月份:1-12
            for (var m = 1; m <= 12; m++) {
                $month.add(new Option(m + ' 月', m));
            }
            $month.value = curMonth;

            // 日期:根據年月渲染
            updateDays();
            $day.value = curDay;
        }

        // 閏年判斷
        function isLeapYear(year) {
            year = parseInt(year, 10);
            return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
        }

        // 取得某年某月天數
        function getDaysInMonth(year, month) {
            if (month === 2) return isLeapYear(year) ? 29 : 28;
            return MON_DAYS[month - 1];
        }

        // 更新日期下拉選單
        function updateDays() {
            var year = parseInt($year.value, 10);
            var month = parseInt($month.value, 10);
            
            // 清空並重建
            $day.innerHTML = '';
            if (!year || !month) return;

            var days = getDaysInMonth(year, month);
            for (var d = 1; d <= days; d++) {
                $day.add(new Option(d + ' 日', d));
            }
            
            // 若原本選的日超過新月份天數,重置為最後一天
            if ($day.value > days) $day.value = days;
        }

        // 組合日期字串寫入隱藏欄位
        function saveDate() {
            var y = $year.value, m = $month.value, d = $day.value;
            if (!y || !m || !d) {
                alert('請完整選擇年月日');
                return;
            }
            // 格式化:YYYY-MM-DD (月日補零)
            var fmt = y + '-' + ('0' + m).slice(-2) + '-' + ('0' + d).slice(-2);
            $hidden.value = fmt;
            alert('已儲存: ' + fmt);
        }

        // 啟動
        init();
    </script>
</body>
</html>

ASP.NET WebForms 整合 (後端取值)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BirthDate.aspx.cs" Inherits="Demo.BirthDate" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>生日選擇</title>
</head>
<body>
    <form id="form1" runat="server">
        <div class="selector-group">
            <asp:DropDownList ID="ddlYear" runat="server" AutoPostBack="false" OnChange="updateDays()"></asp:DropDownList>
            <asp:DropDownList ID="ddlMonth" runat="server" AutoPostBack="false" OnChange="updateDays()"></asp:DropDownList>
            <asp:DropDownList ID="ddlDay" runat="server"></asp:DropDownList>
        </div>
        <asp:HiddenField ID="hfBirthDate" runat="server" />
        <asp:Button ID="btnSave" runat="server" Text="儲存" OnClick="btnSave_Click" OnClientClick="saveDate(); return false;" />
    </form>
    
    <script> ... (同前端邏輯,控制項 ID 對應 ClientID) ... </script>
</body>
</html>

後端 (BirthDate.aspx.cs)

public partial class BirthDate : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // 註冊前端 saveDate() 到按鈕客戶端點擊
            btnSave.Attributes["onclick"] = "saveDate(); return false;";
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string dateStr = hfBirthDate.Value; // 格式: 1990-05-15
        if (DateTime.TryParse(dateStr, out DateTime birthDate))
        {
            // 存入資料庫、計算年齡等...
            Response.Write("儲存成功: " + birthDate.ToString("yyyy-MM-dd"));
        }
        else
        {
            Response.Write("日期格式錯誤");
        }
    }
}

現代化改寫建議 (ES6 Module / Web Component)

// birth-date-picker.js
export class BirthDatePicker extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.innerHTML = `
            
            
            
            
            
        `;
        this.$year = this.shadowRoot.getElementById('year');
        this.$month = this.shadowRoot.getElementById('month');
        this.$day = this.shadowRoot.getElementById('day');
        this.$hidden = this.shadowRoot.getElementById('hidden');
        this.init();
    }
    // ... 移植上述邏輯 ...
    get value() { return this.$hidden.value; }
    set value(v) { /* 解析並設定三個 select */ }
}
customElements.define('birth-date-picker', BirthDatePicker);

使用:<birth-date-picker name="birth"></birth-date-picker>

總結

三級聯動核心在於 年/月變動 → 重算該月天數 → 重渲染日下拉選單。關鍵細節:閏年判斷、日數超出時自動修正、格式化輸出。現代專案建議封裝為 Web Component 或框架元件 (Vue/React),支援 v-model、驗證、無障礙、國際化 (年曆制)。

copyright © 萬盛學電腦網 all rights reserved