简体   繁体   中英

Combine two functions for JQuery DatePicker BeforeShowDay

How do I create a function that combines this first function that disables specific days of the week ;

function disableweekdays(date) {
    var day = date.getDay();
    return [(day != 0 && day != 2 && day != 4 && day != 5), ""];  
} 

with this second function that disables special days of the year ;

function disablespecialdays(date){
    var array = ["12-25", "01-01"]
    var string = jQuery.datepicker.formatDate('mm-dd', date);
    return [ array.indexOf(string) == -1 ]
}

so that their results can be combined for the beforeShowDay in;

$("#myid").datepicker({
    beforeShowDay: disableweekdays,
    minDate: 0, 
    dateFormat: 'dd-MM-yy',
    inline: true,
    showOtherMonths: true,
    dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
})

You can combine both conditions using the && logical operator. it would need to pass all conditions to display the current date for the plugin. I used Array#contains rather that Array#indexOf as it's easier to understand.

 // mock jQuery.datepicker.formatDate const pad = x => x < 10 ? '0' + x : x const jQuery = { datepicker: { formatDate: (format, date) => `${pad(date.getMonth() + 1)}-${pad(date.getDate())}` }} function disableDays(date) { var day = date.getDate(); var datestamp = jQuery.datepicker.formatDate('mm-dd', date) var specialDays = ["12-25", "01-01"] return ( day !== 0 && day !== 2 && day !== 4 && day !== 5 && !specialDays.includes(datestamp) ) } // test the functions console.log( disableDays(new Date()) // depends on the day and date ) console.log( disableDays(new Date('12-25-2017')) // expect false if not sun, tue, thur, fri ) console.log( disableDays(new Date('12-26-2017')) // expect true ) 
 <script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM