I am trying to dynamically add a class to a number of "td" within the jQuery UI datepicker based on the values from "periodValue" and "periodType".
I am having serious trouble in implementing a method of adding the class "your-custom-class" to the x-number of days directly after the current day.
For instance, if today is 29/12/2023 [29] then in my coded example, the next 5 days should have the class "your-custom-class". So this would be: 30/12/2023, 31/12/2023, 01/01/2024, 02/01/2024 and 03/01/2024.
$(document).ready(function() {
let periodValue = 5;
let periodType = d;
$('.input .date').each(function() {
$(this).on('click', function() {
let inputContainer = $(this).closest('.input');
if (inputContainer.hasClass('kn-custom-calendar-confirmation-period')) {
addCustomClassToDates(periodValue, periodType);
} else {
removeCustomClassToDates();
}
});
});
// Initialize datepickers with change event
$('.input .date').each(function() {
var inputId = $(this).attr('id');
var $input = $('#' + inputId);
$input.datepicker({
// Other datepicker options...
onChangeMonthYear: function(year, month, inst) {
updateCustomClasses();
}
}).on('change', updateCustomClasses);
});
});
function updateCustomClasses() {
let inputContainer = $('.input.kn-custom-calendar-confirmation-period');
if (inputContainer.length > 0) {
let periodValue = parseInt(inputContainer.data('periodValue'), 10);
let periodType = inputContainer.data('periodType');
addCustomClassToDates(periodValue, periodType);
} else {
removeCustomClassToDates();
}
}
function addCustomClassToDates(periodValue, periodType) {
var currentDate = new Date(); // Get today's date
var endDate = calculateEndDate(currentDate, periodValue, periodType); // Calculate end date
$("#ui-datepicker-div .ui-datepicker-calendar tbody td").each(function() {
var tdDate = $(this).data('year') + '-' + ($(this).data('month') + 1) + '-' + $(this).text().trim();
tdDate = new Date(tdDate);
if (tdDate > currentDate && tdDate <= endDate) {
$(this).addClass('your-custom-class');
}
});
}
function calculateEndDate(startDate, periodValue, periodType) {
var endDate = new Date(startDate);
switch (periodType) {
case 'd':
endDate.setDate(endDate.getDate() + periodValue);
break;
case 'm':
endDate.setMonth(endDate.getMonth() + periodValue);
break;
case 'y':
endDate.setFullYear(endDate.getFullYear() + periodValue);
break;
}
return endDate;
}
function removeCustomClassToDates() {
$("#ui-datepicker-div .ui-datepicker-calendar tbody td").removeClass('your-custom-class');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>