Question

I would like to highlight date ranges on a jQuery datepicker.

  var dates = new Array();
  dates[0] = [new Date(2014,2,23), new Date(2014,2,30)];
  dates[1] = [new Date(2014,2,13), new Date(2014,2,20)];

  $(function() {
    $('#datepicker').datepicker({
        numberOfMonths: 1,
        minDate: '-0m',
        beforeShowDay: function (date) {
            for (i=0;i<dates.length;i++) {
                var date1 = dates[i][0];
                var date2 = dates[i][1];
                return [true, date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : ""];
            }
        }
    })
  });

The above doesn't work since only one range is visible. How can I get a loop going so that it highlights more than one range? Thanks for your help!

Fiddle

Was it helpful?

Solution

The problem is that you have the return inside the loop for that reason on the end of the first loop the function is returning true or false

You should do something like:

var dates = new Array();
  dates[0] = [new Date(2014,2,23), new Date(2014,2,30)];
  dates[1] = [new Date(2014,2,13), new Date(2014,2,20)];

  $(function() {
    $('#datepicker').datepicker({
        numberOfMonths: 1,
        minDate: '-0m',
        beforeShowDay: function (date) {
            var bool = true;
            for (i=0;i<dates.length;i++) {
                var date1 = dates[i][0];
                var date2 = dates[i][1];
                bool = bool && date1 && ((date.getTime() == date1.getTime()) || (date2 && date >= date1 && date <= date2)) ? "dp-highlight" : "";
            }
            return bool;
        }
    })
  });

OTHER TIPS

Try

var dates = new Array();
dates[0] = [new Date(2014, 2, 23), new Date(2014, 2, 30)];
dates[1] = [new Date(2014, 2, 13), new Date(2014, 2, 20)];

$(function () {
    $('#datepicker').datepicker({
        numberOfMonths: 1,
        minDate: '-0m',
        beforeShowDay: function (date) {
            var flag = false,
                date1, date2, i;
            for (i = 0; i < dates.length; i++) {
                date1 = dates[i][0];
                date2 = dates[i][1];

                flag = (!date1 || date.getTime() >= date1.getTime()) && (!date2 || date.getTime() <= date2.getTime())
                if (flag) {
                    break;
                }
            }
            return [true, flag ? "dp-highlight" : ""];
        }
    })
});

Demo: Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top