jQueryで年月日セレクタを用意する

(1/1)
PHPで年月日を入力(プルダウン方式)」では、うるう年や月の大小(30日、31日など)によって日のセレクタで選択できる値が変化するPHPプログラムを紹介したが、これは、セレクタを選ぶたびにHTTP通信が発生してしまう。そこで今回は、いちいち通信せず、クライアント側で値を変化させるスクリプトを紹介する。
なお、jQuery UI:Datepickerを用いてカレンダーから年月日入力するプログラムは、「PHPで日付入力:カレンダーから選択」で紹介している。

目次

サンプル・プログラムの実行例

jQueryで年月日セレクタを用意する

サンプル・プログラム

圧縮ファイルの内容
jsdate.htmlサンプル・プログラム本体。

プログラムの目標

左図のような年月日セレクタを実装する。

存在しない日付が入力されないように、月の大小によって日のセレクタで選択できる値が最大28,30,31に変化するようにする。また、うるう年の場合は、2月29日が選択できるようにする。

プログラムの流れ

目標を達成するには、年・月・日いずれかのセレクタが変更されたら、年・月・日のセレクタの内容を更新する。つまり、下図のようなスクリプトを組めばよい。
jQueryで年月日セレクタを用意する
jQueryを利用することで、比較的短いコードでこの流れを実装できる。

解説:初期設定

0022: /**
0023:  * 初期設定
0024: */
0025: $(function() {
0026:     //初期値は今日の日付
0027:     var date = new Date();
0028:     setSelector(date.getFullYear(), date.getMonth() + 1, date.getDate());
0029:     //年セレクタ変更時の動作
0030:     $('#year').change(function() {
0031:         var y = $('#year  option:selected').val();
0032:         var m = $('#month option:selected').val();
0033:         var d = $('#date  option:selected').val();
0034:         setSelector(ymd);
0035:     });
0036:     //月セレクタ変更時の動作
0037:     $('#month').change(function() {
0038:         var y = $('#year  option:selected').val();
0039:         var m = $('#month option:selected').val();
0040:         var d = $('#date  option:selected').val();
0041:         setSelector(ymd);
0042:     });
0043: 
0044:     var refere = 'https://www.pahoo.org/e-soul/webtech/js01/js01-06-01.shtm';
0045:     $('#title').html('年月日セレクタ  <span style="font-size:small;">' + yyyymmdd() + '版</span>');
0046:     $('#refere').html('参考サイト:<a href="' + refere +'">' + refere + '</a>');
0047: });

セレクタのID名は、年が year、月が month、日が date とする。
また、年・月・日のセレクタをつくるユーザー関数を setSelector(year, month, date) とする

初期設定は、getMonthメソッドで今日の年月日を取り出し、それを setSelector に渡すだけである。

解説:うるう年の判定

0058: /**
0059:  * 閏年かどうか判定する
0060:  * @param   int year 西暦年
0061:  * @return  bool true:閏年である/false:平年である
0062: */
0063: function isleap(year) {
0064:     var res = false;
0065:     if (year % 4 == 0)      res = true;
0066:     if (year % 100 == 0)    res = false;
0067:     if (year % 400 == 0)    res = true;
0068:     return res;
0069: }

うるう年かどうかを判定する関数 isleap(year) は、「PHPで閏年かどうか判定する」で紹介したPHPプログラムをJavaScriptに移植したものである。

解説:指定した月の日数

0071: /**
0072:  * 指定した月の日数を返す
0073:  * @param   int year  西暦年
0074:  * @param   int month月
0075:  * @return  int日数/FALSE:引数の異常
0076: */
0077: function getDaysInMonth(yearmonth) {
0078:     var days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
0079: 
0080:     if (month < 1 || month > 12)    return FALSE;
0081:     days[2] = isleap(year) ? 29 : 28;       //閏年の判定
0082: 
0083:     return days[month];
0084: }

指定した月の日数(28~31)を返す関数 getDaysInMonth(year, month) は、「PHPで祝日を求める」で紹介したPHPプログラムをJavaScriptに移植したものである。

解説:年月日セレクタをつくる

0086: /**
0087:  * 年月日セレクタをつくる
0088:  * @param   int year  西暦年
0089:  * @param   int month月
0090:  * @param   int date  日
0091:  * @return  int日数/FALSE:引数の異常
0092: */
0093: function setSelector(yearmonthdate) {
0094:     //年セレクタ
0095:     var html = '';
0096:     for (i = -2; i <= +2; i++) {
0097:         if (i == 0)     selected = ' selected';
0098:         else            selected = '';
0099:         yy = parseInt(year) + parseInt(i);
0100:         html += '<option value="'+ yy + '"' + selected + '>'+ yy + '</option>';
0101:     }
0102:     $('#year').html(html);
0103: 
0104:     //月セレクタ
0105:     var html = '';
0106:     for (mm = 1; mm <= 12; mm++) {
0107:         if (mm == month)    selected = ' selected';
0108:         else                selected = '';
0109:         html += '<option value="'+ mm + '"' + selected + '>'+ mm + '</option>';
0110:     }
0111:     $('#month').html(html);
0112: 
0113:     //日セレクタ
0114:     var html = '';
0115:     dm = getDaysInMonth(yearmonth);
0116:     for (dd = 1; dd <= dmdd++) {
0117:         if (dd == dateselected = ' selected';
0118:         else                selected = '';
0119:         html += '<option value="'+ dd + '"' + selected + '>'+ dd + '</option>';
0120:     }
0121:     $('#date').html(html);
0122: }

年月日セレクタを動的に生成するのが関数 setSelector(year, month, date) である。年、月、日と順番にセレクタを生成してゆく。

まず年セレクタであるが、与えられた year±2の範囲でセレクタを生成する。値がyearと等しかったら、selected属性を付与する。

月セレクタは、常に1から12までのセレクタを生成する。値がmonthと等しかったら、selected属性を付与する。

日セレクタは、先ほど紹介した関数 getDaysInMonth の戻り値によってセレクタを生成する。値がdateと等しかったら、selected属性を付与する。

解説:HTMLボディ

0128: <form name="myform">
0129: <select name="year"  id="year"></select>年
0130: <select name="monthid="month"></select>月
0131: <select name="date"  id="date"></select>日
0132: </form>

静的HTMLは上述の通り。

質疑応答

【質問】
takuo さん
大変参考になっております。有難うございます。
生年月日、結婚記念日と死亡年月日を入力するための日付セレクトボックスを作りたいのですが、うまくいきません。
よろしくお願いします。(MacのGoogle Chrome)
【回答】
実行例の画像を掲示しました。
この通りの画面にならないようでしたら、作成したJavaScriptをお知らせください。お力になれるかもしれません。

参考サイト

(この項おわり)
header