自分用のメモです
下記のサイトを参考にしてつくった
qiita.com
日付セレクトボックスに初期値を設定するためには、
Counter関数を呼び出した後で、特定の年月日を選択状態にする処理を追加する必要があります。初期値を設定するには、option要素のselected属性をtrueに設定します。
以下のステップで初期値を設定する方法を示します。
- showYearCounter関数に初期値を設定するための引数を追加します(例:defaultYear, defaultMonth, defaultDay)。
- Counter関数に初期値を渡して、その値に対応するoption要素を選択状態にします。
- Counter関数内で、渡された初期値(もしあれば)に基づいて、該当するoptionのselected属性をtrueに設定します。
<!DOCTYPE html>
<html>
<head>
<title>日付選択</title>
<script>
function Counter(elementId, start, end, defaultValue) {
const element = document.getElementById(elementId);
element.innerHTML = '';
for (let i = start; i <= end; i++) {
let option = document.createElement("option");
option.value = i;
option.text = i;
if (i === defaultValue) {
option.selected = true;
}
element.appendChild(option);
}
}
function showYearCounter(yearId, monthId, dayId, defaultYear, defaultMonth, defaultDay) {
Counter(yearId, 1900, 2020, defaultYear);
Counter(monthId, 1, 12, defaultMonth);
showdayCounter(yearId, monthId, dayId, defaultDay);
}
function showdayCounter(yearId, monthId, dayId, defaultDay) {
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, defaultDay);
} else if (month.match(/^(4|6|9|11)$/)) {
Counter(dayId, 1, 30, defaultDay);
} else {
Counter(dayId, 1, 31, defaultDay);
}
}
function leap(year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
</script>
</head>
<body>
<body onload="showYearCounter('year', 'month', 'day', 2000, 1, 1);">
<select id="year" onchange="showdayCounter('year', 'month', 'day');"></select>年
<select id="month" onchange="showdayCounter('year', 'month', 'day');"></select>月
<select id="day"></select>日
</body>
</html>
選択した内容を保存または表示させる必要がある場合はイベントリスナーを追加する必要がある
document.getElementById('year').addEventListener('change', updateDate);
document.getElementById('month').addEventListener('change', updateDate);
document.getElementById('day').addEventListener('change', updateDate);
function updateDate() {
const year = document.getElementById('year').value;
const month = document.getElementById('month').value;
const day = document.getElementById('day').value;
if (!year || !month || !day) return;
const formattedDate = `${year}年${month}月${day}日`;
console.log(formattedDate);
document.getElementById('selectedDate').textContent = formattedDate;
localStorage.setItem('selectedDate', formattedDate);
}
function initAndUpdateDate() {
showYearCounter('year', 'month', 'day', 2000, 1, 1);
updateDate();
}
initAndUpdateDate();