jQuery ui: multiple ranges for date picker?

后端 未结 1 639
[愿得一人]
[愿得一人] 2020-12-09 13:13

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

相关标签:
1条回答
  • 2020-12-09 13:30

    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 :)

    0 讨论(0)
提交回复
热议问题