views:

15

answers:

1

I want to use the jquery-ui datepicker for my project, but I need to be able to have multiple, disjoint ranges of valid dates. Dates not in one of these ranges shouldn't be selectable.

 $(function() {
 $("#datepicker").datepicker({
   numberOfMonths: 1,
   minDate: new Date(2010, 8, 1), //range 1
   maxDate: new Date(2010, 8, 20) //range 1
   minDate: new Date(2010, 9, 1), //range 2
   maxDate: new Date(2010, 9, 20) //range 2
 });
 });

How would I go about implementing this? I'd appreciate any help.

+1  A: 

You could use beforeShowDay to restrict the range when displaying months, like this:

var d1s = new Date(2010, 8, 1),
    d1e = new Date(2010, 8, 20),
    d2s = new Date(2010, 9, 1),
    d2e = new Date(2010, 9, 20);

$(function() {
  $("#datepicker").datepicker({
    numberOfMonths: 1,
    beforeShowDay: function(date) {
      return [(date >= d1s && date <= d1e || date >= d2s && date <= d2e), ''];
    },
    minDate: d1s,
    maxDate: d2e
  });
});​

You can give it a try here


Or, here's a slightly less efficient but more flexible approach for any number of date ranges:

var ranges = [ { start: new Date(2010, 8, 1), end: new Date(2010, 8, 20) },
               { start: new Date(2010, 9, 1), end: new Date(2010, 9, 20) },
               { start: new Date(2010, 10, 1), end: new Date(2010, 10, 20) } ];

$(function() {
  $("#datepicker").datepicker({
    numberOfMonths: 1,
    beforeShowDay: function(date) {
        for(var i=0; i<ranges.length; i++) {
          if(date >= ranges[i].start && date <= ranges[i].end) return [true, ''];
        }
        return [false, ''];
    },
    minDate: ranges[0].start,
    maxDate: ranges[ranges.length -1].end
  });
});​

You can give this version a try here, just put the ranges in chronological order :)

Nick Craver