Niels Temmerman
Niels Temmerman

Reputation: 51

Enable specific dates in bootstrap datepicker

I have a bootstrap datepicker (https://github.com/uxsolutions/bootstrap-datepicker) on my website, and I have an array of days which I want to enable and disable all the other dates in the datepicker. How can I code this?

How can I pass this in?

var enableDays = "24-07-2019, 20-08-2019, 22-08-2019, 13-09-2019"
$(function () {
    $('#deliveryDate').datepicker({
        maxViewMode: 2,
        weekStart: 1,
        startDate: '+1d',
        autoclose: true,
        todayHighlight: true,
        format: "dd-mm-yyyy", 
        clearBtn: true,
        language: form.UILanguage(),
        autoclose: true,
    }) 
});

Upvotes: 5

Views: 8296

Answers (1)

Paweł Kuffel
Paweł Kuffel

Reputation: 471

In the docs of Bootstrap Datepicker, you can find beforeShowDay option.

You can define a function that would return {enabled: false} for every day that is not included in a given list.

Here is a complete implementation:

//we start with splitting the provided string into an array
var enableDays = "24-07-2019, 20-08-2019, 22-08-2019, 13-09-2019".split(', ')

function formatDate(d) {
  var day = String(d.getDate())
  //add leading zero if day is is single digit
  if (day.length == 1)
    day = '0' + day
  var month = String((d.getMonth()+1))
  //add leading zero if month is is single digit
  if (month.length == 1)
    month = '0' + month
  return day + "-" + month + "-" + d.getFullYear()
}

$(function () {
  $("#deliveryDate").datepicker({ 
        maxViewMode: 2,
        weekStart: 1,
        startDate: "+1d",
        beforeShowDay: function(date){
          if (enableDays.indexOf(formatDate(date)) < 0)
            return {
              enabled: false
            }
          else
            return {
              enabled: true
            }
        },
        todayHighlight: true,
        format: "dd-mm-yyyy", 
        clearBtn: true,
        autoclose: true
  })
});

Since date formatting functionality in pure JS is limited, I've written a function that returns a String in dd-mm-yyyy format. Feel free to use any date manipulation library (like moment.js) instead.

Upvotes: 11

Related Questions