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

纵然是瞬间 提交于 2020-01-07 03:57:06

问题


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());
});

回答1:


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




回答2:


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;">


来源:https://stackoverflow.com/questions/45436828/bootstrap-datepicker-how-can-i-set-limit-to-select-3-dates-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!