LoginSignup
1
0

javascriptで日付セレクトボックスを作る

Last updated at Posted at 2023-10-22
日付チェックボックス
<!DOCTYPE html>
<html>

<head>
    <title>日付選択</title>
    <script>
        //数値カウンターまとめ
        function Counter(elementId, start, end) {
            document.getElementById(elementId).innerHTML = '';
            for (let i = start; i <= end; i++) {
                let option = document.createElement("option");
                option.value = i;
                option.text = i;
                document.getElementById(elementId).appendChild(option);
            }
        }

        //年月はまとめてカウンターに渡して生成
        function showYearCounter(yearId, monthId, dayId) {
            Counter(yearId, 1800, 2020);
            Counter(monthId, 1, 12);
            showdayCounter(yearId, monthId, dayId);
        }

        //日だけ年月で3パターンを判定してカウンター関数に投げる
        function showdayCounter(yearId, monthId, dayId) {
            let year = document.getElementById(yearId).value;
            let month = document.getElementById(monthId).value;
            let februaryDays = leap(year) ? 29 : 28;

            if (month == 2) {
                Counter(dayId, 1, februaryDays);
            } else if (month.match(/^(4|6|9|11)$/)) {
                Counter(dayId, 1, 30);
            } else {
                Counter(dayId, 1, 31);
            }
        }

        //閏年判定
        function leap(year) {
            return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        }

    </script>
</head>

<body>

    <body onload="showYearCounter('year', 'month', 'day');">
        <select id="year" onchange="showdayCounter('year', 'month', 'day');"></select><select id="month" onchange="showdayCounter('year', 'month', 'day');"></select><select id="day"></select></body>

</html>
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0