Elymentree
Elymentree

Reputation: 853

JQuery Datepicker restrict to bi-weekly

How do I restrict the JQuery Datepicker to show only bi-weekly Saturdays. I have successfully restricted it to show only weekly but could not figure out how to make it bi-weekly. See sample code below for weekly filter that allows for Saturdays only.

$("#datefilter").datepicker({ 
    beforeShowDay: function(date){ 
        if(date.getDay() === 6){
            return [true];
        }else{
            return [false];
        }  
});

Upvotes: 2

Views: 178

Answers (2)

Nenad
Nenad

Reputation: 26727

Did not test too much, but this should work for 1st and 3rd Saturday (5th too):

$(function() {
    $("#datepicker").datepicker({ 
        beforeShowDay: function(date){
          var dayOfMonth = date.getDate()
            if(date.getDay() === 6 && Math.floor((dayOfMonth - 1) / 7) % 2 === 0){
                return [true];
            }else{
                return [false];
            }
        }
    });
});

And if you want 2nd and 4th, replace 0 with 1 in 2nd part of if condition:

Math.floor((dayOfMonth - 1) / 7) % 2 === 1

UPDATE corrected calculation, should be (dayOfMonth - 1).

Upvotes: 1

Brian Hadley
Brian Hadley

Reputation: 135

This is another option, if you anticipate needing to change to another day of the week you can seed it with a date that falls on that day:

function isAlternatingDay(testDate){
    var seedDay = new Date(2018,11,3);
    var daysDiff = (testDate - seedDay)/86400000;

    return daysDiff % 14 === 0;
}

Upvotes: 1

Related Questions