jQuery UI DatePicker – How to silently stop execution of a certain callback function?

I’m using jquery UIs datepicker to pick a date, with a certain condition. The user cannot select a date within one week from today. The problem is, how do I silently stop the callback function from being executed when the user selects a bad date? The datepicker automatically colors every date the user clicks on. I’ve tried throw new Error; but obviously this is an ugly solution. The demo can be found on JSfiddle.

Here’s the JS logic so far:

var selectedStartingDate;
var todayRightNow; //holds today's date as Milliseconds
var tempArrayOfNextDates = []; //holds the following week after the selected date as MilliSeconds, easy for comparing days and dates
var dateToday = new Date(); 
$(function(){
    $('#datepicker').datepicker({
        onSelect: function(dateText, inst){
            selectedStartingDate = dateText;
            var selectedDateAsObject = $(this).datepicker('getDate');
            arrayOfFollowingWeekDates = calcFollowingtWeekDates(selectedDateAsObject);
        },
        minDate: dateToday,
        showOtherMonths: true
    });
});

//this func calculates one week ahead of the given date
function calcFollowingtWeekDates(selectedDateObj){
    var rightNow = new Date();
    rightNow.setHours(0);
    rightNow.setMinutes(0);
    rightNow.setSeconds(0);
    rightNow.setMilliseconds(0);
    todayRightNow = rightNow.getTime();
    var day;
    var prevDay=todayRightNow;
    var followingWeek = []; //holds the following 7 days from the selected date as a JS Date object

    var selectedDateInMilliseconds = selectedDateObj.getTime();

    console.log("selected date in milliseconds: "+selectedDateInMilliseconds);
    tempArrayOfNextDates[0]=todayRightNow;
    for(var i=0;i<7;i++){
        tempArrayOfNextDates[i] = 86400000 + prevDay;
        day = new Date(tempArrayOfNextDates[i]);
        prevDay = tempArrayOfNextDates[i];
        followingWeek[i]=day;
    }

    if(tempArrayOfNextDates.indexOf(selectedDateInMilliseconds)>-1){
        alert("choose date one week from today");
        throw new Error; //****************  how do I stop here SLIENTLY?!
    }else{
        return followingWeek;
    }
}


Source: jquery

Leave a Reply