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
関連記事
-
-
NicEdit(WYSIWYGエディタ)とテキストエリアの切り替え
チェックボックスのON / OFFでNicEdit(WYSIWYGエディタ)とt ...
-
-
Ajaxで負荷軽減
業務中、専用のページでfile_get_contents的なものは あまり使わな ...
-
-
アンカーリンクでURLに「#hoge」のようなパラメータを残さずスクロールさせる方法
アンカータグをクリックしてもブラウザのURL欄に「#hoge」のようなハッシュを ...
-
-
画像をドラッグ&ドロップでアップロード
■2015/04/15追記 以下記事の方が新しくて詳しい。 http://tai ...
-
-
テキストエリアを選択すると中身を全選択状態にする方法
テキストエリアやテキストボックスの中に文字が書いてあり、ドラッグをしなくても、そ ...