このために、任意の年月の月末日を得る必要があります。例を示します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function(){ | |
// 年、月、日のプルダウンの参照を取得(idがそれぞれyear, month, dayであるとする) | |
var year = $('#year'); | |
var month = $('#month'); | |
var day = $('#day'); | |
var endDay; | |
year.change(function(){ | |
endDay = getMonthEndDay(year.val(), month.val()); | |
day.children().remove(); | |
for (var i=0; i<endDay; i++) { | |
day.append($('<option>').attr({ value: 1+i }).text(1+i)); | |
} | |
}); | |
month.change(function(){ | |
endDay = getMonthEndDay(year.val(), month.val()); | |
day.children().remove(); | |
for (var i=0; i<endDay; i++) { | |
day.append($('<option>').attr({ value: 1+i }).text(1+i)); | |
} | |
}); | |
}); | |
/** | |
* 年月を指定して月末日を求める関数 | |
* year 年 | |
* month 月 | |
*/ | |
function getMonthEndDay(year, month) { | |
// 通常、new Date()にはmonth - 1を渡すところ、monthをそのまま渡す。 | |
// するとそのままでは次月の指定になるが、日に0を指定すると前月の末日の指定になる。 | |
// これによって任意年月の末日を得る。 | |
var dt = new Date(year, month, 0); | |
return dt.getDate(); | |
} |
例では、任意の月末日を得たのち、年、月のプルダウンが変化(change)するタイミングで、その時の年、月の組み合わせで月末日(endDay)を求めて、この値を使って動的に日のselectのoption要素を動的に生成しています。
参考
JavaScript による日付・時刻・時間の計算・演算のまとめ – hoge256 blog
0 件のコメント:
コメントを投稿