jQuery UIのDatepickerでリセット(入力内容消去)ボタンの追加方法
jQuery UIのDatepickerでキーボード入力を防ぎたいためreadonly属性をつけた。そうすると今後は一度ピッカーから日付を選択すると内容をリセットできなくなる(Deleteキー等が入力できないため)。そこで入力内容をリセットするボタンを設置したい。以下に対応方法をメモ。
Datepickerの基本的な使い方
jQuery UIのDatepickerの基本的な使い方は過去記事を参照。
サンプル
https://taitan916.info/sample/jquery-ui-datepicker/index4.html
ソースコード
<html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>jQuery UIDatepicker sample</title> <script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/listjs/2.3.1/list.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/i18n/jquery.ui.datepicker-ja.min.js"></script> </head> <body> <input type="text" id="date" readonly> <script> $(function(){ $(`#date`).datepicker({ dateFormat: 'yy-mm-dd', showButtonPanel : true, beforeShow : function(input, instance) { addResetBtn(instance); }, onChangeMonthYear: function(year, month, instance) { addResetBtn(instance); }, }); function addResetBtn(instance) { setTimeout(function () { $(`[data-handler="today"], [data-handler="hide"]`).hide(); const buttonPane = $(instance).datepicker(`widget`).find(`.ui-datepicker-buttonpane`); const btn = $(`<button class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" type="button">リセット</button>`); btn.unbind(`click`).bind(`click`, function () { $.datepicker._clearDate(instance.input); }); btn.appendTo(buttonPane); }, 1); } }); </script> </body> </html>
解説等
ボタンパネルの表示
リファレンスの通り「showButtonPanel : true」を指定することでボタンパネルが表示される。
ただ、こちらはリセットボタンではなく「今日」「閉じる」の2つのボタンが表示されるというオプションになる。
「今日」「閉じる」の2つは不要なので「$(`[data-handler="today"], [data-handler="hide"]`).hide();」で非表示にしている。
リセットボタンの表示
addResetBtn()がリセットボタン表示用の関数になる。onChangeMonthYearの際にも呼び出しておかないと翌月もしくは前月に移動した際にリセットボタンが表示されないので注意。
参考サイト
https://stackoverflow.com/questions/4917779/jquery-datepicker-date-reset
関連記事
-
-
jQuery UIを用いた日付及び時間のピッカーの利用方法
jQuery UIを用いた日付及び時間のピッカーを実装したい。以下にソースコード ...
-
-
jQueryの通知メッセージ用ライブラリ「Toastr」の利用方法
あるサイトのソースコードを拝見しているとToastrというJSファイルをCDNで ...
-
-
jQueryで特定のdata属性をセレクタとして指定する方法
jQueryで特定のdata属性をクリックした際に何らかのイベントを実行したかっ ...
-
-
formでファイルを選択した際にファイル名やサイズ、形式を調べる方法
フォームで画像などをアップロードする際に「ファイルサイズが大きすぎないか?」「拡 ...
-
-
セレクトメニュー(プルダウン)をdisplay:none;指定してもiPhoneのみ非表示にならない問題の対応方法
セレクトメニュー(プルダウン)に対してdisplay:none;指定したりjQu ...