【jQuery】Datepickerで期間指定して、なおかつNGな日を取得するサンプル

フォームなどでカレンダー表示させる「Datepicker」は今でもよく使われるプラグインですが、イベント等のLPなどで予約フォームを作る際に、期間を限定して、なおかつ定休日などのNGな日を指定して、ユーザーに選ばれないようにするというやり方をご紹介します。

まずはDatepickerの簡単な使い方から。

Datepickerを導入する方法

Datepickerは他のjQueryプラグインと同様、必要なJavaScriptとCSSファイルを読み込んで、オプションを決めるといった流れです。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.min.css">

オプションの書き方

<script>
    $(function(){
        $("#datepicker").datepicker();
    });
</script>

この辺りの詳しい情報はhttps://agohack.com/jquery-ui-datepicker/を参照ください。

期間限定&NGな日を決めるサンプル

<script>
$(function() {
    var dateFormat   = 'yy/mm/dd';
    var disableDates = ['2022/12/14','2022/12/15','2022/12/19','2022/12/21'];//NGな日を決める
    $('#datepicker').datepicker({//IDを指定
        dateFormat: dateFormat,
        minDate: new Date(2022, 12 - 1, 10),//期間の始まり(これは12月10日)
        maxDate: new Date(2022, 12 - 1, 23),//期間の終わり(これは12月23日)
        beforeShowDay : function(date) {
        var disableDate = $.datepicker.formatDate(dateFormat, date);
        if (disableDates.indexOf(disableDate) !== -1) {
                return [false, ''];
            }
            return [true, ''];
        },
    });
});
</script>

指定した日と期間を書き換えればそのまま使えます。

ネットでdatepickerの期間限定や、NGな日の指定といったサンプルはありましたが、この2つが同時に指定されているサンプルがなかったので書いてみました。

 

 

 

About the author

Kazuhito Naozuka Representative Director / Web Director / Programmer

Based in Saga City, supporting web strategy for small and medium-sized businesses and sole proprietors. Handling everything from website creation to SaaS development, SEO optimization, and ad management across the digital domain. Our mission is to accelerate the growth of regional businesses through "technical expertise × strategic proposals." We have been involved in numerous projects to date.