勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

jQuery UIのDatepickerでリセット(入力内容消去)ボタンの追加方法

  jQuery JavaScript

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 JavaScript

  関連記事

jQuery Nice Selectを特定ページのみ無効にする方法

bootstrap系のテンプレートデザインを使用したサイトを構築中に、セレクトメ ...

表示範囲を自由に変更可能な折れ線グラフが表示できるJSライブラリ amCharts の使用方法

どこかのサイトを閲覧していた際に、恐らくはJavaScriptのライブラリで描写 ...

pjaxについてのメモ

ずっと気になっていたpjaxについてのメモ。 ■参考サイト http://chi ...

JavaScript / jQueryでブラウザのウィンドウがアクティブかどうかを判別する方法

ある動画サイトを閲覧していた際にウィンドウが非アクティブになると視聴中の動画が止 ...

セレクトメニューにサジェスト機能をつける方法(select2)

formのselectメニューで何文字が入力すると候補を絞って表示させるサジェス ...