nsilva nsilva - 6 months ago 27
Javascript Question

jQuery Datepicker Exclusion Days

I have the following jQuery code:-

var excludedDays = jQuery('#exclude-values').val();
// above returns = ["05/16/2016","05/17/2016"];

var disabledDays = ["5/16/2016","5/17/2016"];

function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '/' + d + '/' + y,disabledDays) != -1 || new Date() > date) {
return [false];
}
}
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}

jQuery('#datepicker').datepicker({
dateFormat: 'dd-mm-yy',
changeYear: false,
minDate: 7,
inline: true,
constrainInput: true,
beforeShowDay: noWeekendsOrHolidays
});


This is working, however it only works if the value passed is in the format m/dd/yyyy when I need it to be mm/dd/yyyy.

How would I go about amending the code so it would work with the format of my
excludedDays
?

Answer

Just append a zero if the month+1 is one digit? As per my snippet?

var excludedDays = jQuery('#exclude-values').val();
// above returns = ["05/16/2016","05/17/2016"];

var disabledDays = ["05/16/2016","05/17/2016"];

function nationalDays(date) {
    var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
    
    for (i = 0; i < disabledDays.length; i++) {
       
        if($.inArray( ((m+1<10) ?  "0"+parseInt(m+1) : m+1) + '/' + d + '/' + y,disabledDays) != -1 || new Date() > date) {
            return [false];
        }
    }
    return [true];
}
function noWeekendsOrHolidays(date) {
    var noWeekend = jQuery.datepicker.noWeekends(date);
    return noWeekend[0] ? nationalDays(date) : noWeekend;
}

jQuery('#datepicker').datepicker({
    dateFormat: 'dd-mm-yy',
    changeYear: false,
    minDate: 7,
    inline: true,
    constrainInput: true,
    beforeShowDay: noWeekendsOrHolidays
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<body>

<p>Date: <input type="text" id="datepicker"></p>
 
 
</body>

Comments