[jquery] jQuery UI Datepicker - Multiple Date Selections

Is there a way to use the jQuery UI Datepicker widget to select multiple dates?

All help is appreciated! If its not posable to use the jquery UI datepicker then is there something similar that does?

This question is related to jquery jquery-ui datepicker ui-select2

The answer is


Just had a requirement for this; here is the code I used. Apply it to an input as normal, I am using the class typeof__multidatepicker.

It maintains a list of unique dates in the owner textbox. You can also type in there, this is not validated - obviously the server needs to check the resulting list!

I tried to get it to work with the datepicker's linked textbox but failed, so it creates an invisible input for the datepicker (it doesn't seem to work with display:none, hence the odd styling).

It is positioned over the main input so the datepicker appears in the correct place, and is 1px in width so you can still type into the main textbox.

It's for an intranet with a fixed platform so I haven't done much cross-browser testing.

Remember to include the handler on the body or it works confusingly.

$('.typeof__multidatepicker').each(
    function()
    {
        var _this = $(this);                        

        var picker = $('<input tabindex="-1" style="position:absolute;opacity:0;width:1px" type="text"/>');

        picker.insertAfter(this)
        .position({my:'left top', at:'left top', of:this})
        .datepicker({
            beforeShow:
                function()
                {
                    _this.data('mdp-popped', true);
                },
            onClose: 
                function(dt, dpicker)
                {   
                    var date = $.datepicker.formatDate(picker.datepicker('option', 'dateFormat'), picker.datepicker('getDate'));
                    var hash = {};
                    var curr = _this.val() ? _this.val().split(/\s*,\s*/) : [];
                    var a = [];

                    $.each(curr, 
                        function() 
                        { 
                            if(this != '' && !/^\s+$/.test(this)) 
                            {   
                                a.push(this); 
                                hash[this] = true;
                            }
                        }
                    );

                    if(date && !hash[date])
                    {
                        a.push(date);

                        _this.val(a.join(', '));
                    }                                                                   

                    _this.data('mdp-popped', false);
                    _this.data('mdp-justclosed', true);
                }
        }); 

        _this.on('focus', 
            function(e) 
            {                               
                if(!_this.data('mdp-popped') && !_this.data('mdp-justclosed'))
                    _this.next().datepicker('show'); 

                _this.data('mdp-justclosed', false);
            }
        );
    }
);

$('body').on('click', function(e) { $('.typeof__multidatepicker').data('mdp-justclosed', false); });

I have now spent quite some time trying to find a good date picker that support interval ranges, and eventually found this one:

http://keith-wood.name/datepick.html

I believe this may be the best jquery date picker for selecting a range or multiple dates, and it is claimed to have been the base for the jQuery UI datepicker, and I see no reason to doubt that since it seems to be really powerful, and also good documented !


When you modifiy it a little, it works regardless which dateFormat you have set.

$("#datepicker").datepicker({
                        dateFormat: "@", // Unix timestamp
                        onSelect: function(dateText, inst){
                            addOrRemoveDate(dateText);
                        },
                        beforeShowDay: function(date){
                            var gotDate = $.inArray($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), date), dates);
                            if (gotDate >= 0) {
                                return [false,"ui-state-highlight", "Event Name"];
                            }
                            return [true, ""];
                        }
                    });     

Use this plugin http://multidatespickr.sourceforge.net

  • Select date ranges.
  • Pick multiple dates not in secuence.
  • Define a maximum number of pickable dates.
  • Define a range X days from where it is possible to select Y dates. Define unavailable dates

<div id="calendar"></div>
<script>
$(document).ready(function() {
    var days = [];

    $('#calendar').datepicker({
        dateFormat: 'yymmdd',
        showWeek: true, showOtherMonths: false, selectOtherMonths: false,
        navigationAsDateFormat: true, prevText: 'MM', nextText: 'MM',
        onSelect: function(d) {
            var i = $.inArray(d, days);

            if (i == -1)
                days.push(d);
            else
                days.splice(i, 1);
        },
        beforeShowDay: function(d) {
            return ([true, $.inArray($.datepicker.formatDate('yymmdd', d), days) == -1 ? 'ui-state-free' : 'ui-state-busy']);
        }
    });
});
</script>

NOTE: You can prefill days with a list of dates like '20190101' with a piece of code in PHP.

Add 2 lines to your CSS:

#calendar .ui-state-busy a {background:#e6e6e6 !important;}
#calendar .ui-state-free a {background:none !important;}

To get the list of days selected by the calendar in a <form>:

<div id="calendar"></div>
<form method="post">
<input type="submit" name="calendar_get" id="calendar_get" value="Validate" />
</form>

Add this to the <script>:

    $('#calendar_get').click(function() {
        $(this).append('<input type="hidden" name="calendar_days" value="' + days.join(',') + '" />');
    });

Apply implode on the string in $_POST['calendar_days'] and map strtotime to all the formatted dates.


The plugin developed by @dubrox is very lightweight and works almost identical to jQuery UI. My requirement was to have the ability to restrict the number of dates selected.

Intuitively, the maxPicks property seems to have been provided for this purpose, but it doesn't work unfortunately.

For those of you looking for this fix, here it is:

  1. First up, you need to patch jquery.ui.multidatespicker.js. I have submitted a pull request on github. You can use that until dubrox merges it with the master or comes up with a fix of his own.

  2. Usage is really straightforward. The below code causes the date picker to not select any dates once the specified number of dates (maxPicks) has been already selected. If you unselect any previously selected date, it will let you select again until you reach the limit once again.

    $("#mydatefield").multiDatesPicker({maxPicks: 3});


http://t1m0n.name/air-datepicker/docs/? I've have tried several method of multi datepicker but only this works


use this on:

$('body').on('focus',".datumwaehlen", function(){
    $(this).datepicker({
        minDate: -20
    });
});

I needed to do the same thing, so have written some JavaScript to enable this, using the onSelect and beforeShowDay events. It maintains its own array of selected dates, so unfortunately doesn't integrate with a textbox showing the current date, etc. I'm just using it as an inline control, and I can then query the array for the currently selected dates.
I used this code as a basis.

<script type="text/javascript">
// Maintain array of dates
var dates = new Array();

function addDate(date) {
    if (jQuery.inArray(date, dates) < 0) 
        dates.push(date);
}

function removeDate(index) {
    dates.splice(index, 1);
}

// Adds a date if we don't have it yet, else remove it
function addOrRemoveDate(date) {
    var index = jQuery.inArray(date, dates);
    if (index >= 0) 
        removeDate(index);
    else 
        addDate(date);
}

// Takes a 1-digit number and inserts a zero before it
function padNumber(number) {
    var ret = new String(number);
    if (ret.length == 1) 
        ret = "0" + ret;
    return ret;
}

jQuery(function () {
    jQuery("#datepicker").datepicker({
        onSelect: function (dateText, inst) {
            addOrRemoveDate(dateText);
        },
        beforeShowDay: function (date) {
            var year = date.getFullYear();
            // months and days are inserted into the array in the form, e.g "01/01/2009", but here the format is "1/1/2009"
            var month = padNumber(date.getMonth() + 1);
            var day = padNumber(date.getDate());
            // This depends on the datepicker's date format
            var dateString = month + "/" + day + "/" + year;

            var gotDate = jQuery.inArray(dateString, dates);
            if (gotDate >= 0) {
                // Enable date so it can be deselected. Set style to be highlighted
                return [true, "ui-state-highlight"];
            }
            // Dates not in the array are left enabled, but with no extra style
            return [true, ""];
        }
    });
});
</script>

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to datepicker

Angular-Material DateTime Picker Component? $(...).datepicker is not a function - JQuery - Bootstrap Uncaught TypeError: $(...).datepicker is not a function(anonymous function) Get date from input form within PHP Angular bootstrap datepicker date format does not format ng-model value jQuery Datepicker close datepicker after selected date bootstrap datepicker setDate format dd/mm/yyyy bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date Clear the value of bootstrap-datepicker Disable future dates after today in Jquery Ui Datepicker

Examples related to ui-select2

How to get Selected Text from select2 when using <input> How do I change selected value of select2 dropdown with JqGrid? Update select2 data without rebuilding the control set the width of select2 input (through Angular-ui directive) Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio? Can I apply the required attribute to <select> fields in HTML5? jQuery UI tabs. How to select a tab based on its id not based on index How To Get Selected Value From UIPickerView UIButton: set image for selected-highlighted state How can I pass selected row to commandLink inside dataTable or ui:repeat?