Haseeb Ibrar
Haseeb Ibrar

Reputation: 437

Bootstrap Datepicker: How can I set limit to select 3 dates only?

I m using Bootstrap Datepicker how can i set limit to select maximum 3 dates only by using multidates option.

var todayDate = moment().format('mm-dd-yyyy');
dp = $("#leaveDatePicker").datepicker({
    format              : "mm-dd-yyyy",
    multidate           : true,
    inline              : true,
    todayHighlight      : false,
    daysOfWeekDisabled  : [0],
    startDate           : 'today',
    beforeShowDay       : function(date){
         var d          = date;
         var curr_month = d.getMonth() + 1; //Months are zero based
         if(curr_month < 10)
            curr_month = '0'+curr_month;
         var formattedDate = curr_month + "-" + d.getDate() + "-" +d.getFullYear()
        if ($.inArray(formattedDate, myActiveDates) != -1){                 
            return {
              classes: 'active'
            };
        }
        return [true,""];
    }
});
dp.data('datepicker').setDates($('input#datestring').val().split(','));
dp.on('changeDate', function (e){
    $('input#datestring').val($(this).data('datepicker').getFormattedDate());
});

Upvotes: 0

Views: 3031

Answers (2)

Manish Nayak
Manish Nayak

Reputation: 665

No need to do any extra code to set limit for multiple date selection. Just set multidate option with any number that you want to set as multiple date limit. See below example, you will be able to select maximum three dates only.

Example

$("#Txt_Date").datepicker({
    format: 'd-M-yyyy',
    inline: false,
    lang: 'en',
    step: 5,
    multidate: 3,
    closeOnDateSelect: true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>


<input type="text" id="Txt_Date" placeholder="Choose Date" style="cursor: pointer;">

Upvotes: 3

charlietfl
charlietfl

Reputation: 171679

Use a variable to store selected dates array.

Whenever dates are selected check the length of the data in the datepicker and if it is more than 3 do a reset from the stored array and notify user

var selectedDates = [];
dp.on('changeDate', function(e) {

  if (e.dates.length < 4) {
    // store current selections
    selectedDates = e.dates
  } else {
    // reset dates if 4th selected
    dp.data('datepicker').setDates(selectedDates);
    alert('Can only select 3 dates')
  }

});

DEMO

Upvotes: 2

Related Questions