I\'m integrating calender in one of project using moment js.
I want to disable previous date and some other selected date.
I tried but date is not disabled.
In this answer, I'll disect multiple scenarios of yours, using several demos. Each of these have in common the fact that they're adding a disabled
class on some days. I won't repeat this in every demo, so here it is, once:
Inside Calendar.prototype.drawDay
//Outer Day
var outer = createElement('div', this.getDayClass(day));
outer.addEventListener('click', function() {
// Only open if the element is not disabled
if (!this.classList.contains('disabled')) {
self.openDay(this);
}
});
At the end of your CSS
.day.disabled {
color: #888;
cursor: default;
}
You can use MomentJS's isBefore method to determine which days are past and should be disabled, and disable clicks on them.
/* ... */
Calendar.prototype.getDayClass = function(day) {
classes = ['day'];
if(day.month() !== this.current.month()) {
classes.push('other');
} else if (today.isSame(day, 'day')) {
classes.push('today');
}
// Here, add a class to disable past dates
if (day.isBefore(moment(), 'day')) {
classes.push('disabled');
}
return classes.join(' ');
}
/* ... */
JSFiddle demo (I had to remove it from SO, too many characters)
Here, we're going to define an Array containing dates, and use that Array to decide whether or not to disable dates. The dates in your Array can be of any format, but you need to match that format when looking for a date in that Array.
In my example, I use the YYYY-MM-DD
format (you can find other formats here)
/* Have this, somewhere in your code */
var allowedDates = [
'2018-04-14',
'2018-05-01',
'2018-05-02'
/* ... */
];
/* ... */
Calendar.prototype.getDayClass = function(day) {
classes = ['day'];
if(day.month() !== this.current.month()) {
classes.push('other');
} else if (today.isSame(day, 'day')) {
classes.push('today');
}
// Here, add a class to disable disallowed dates
if (allowedDates.indexOf(day.format('YYYY-MM-DD')) < 0) {
classes.push('disabled');
}
return classes.join(' ');
}
/* ... */
JSFiddle demo