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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With