简体   繁体   中英

How to block multiple date ranges in jQuery Datepicker ui

I have this code to go on, but what I would like is have these dates being blocked instead of enabled. So just the other way round. Anyone in the know of how to do this based on this code? Thanks a million!

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
  });
});​

Also, my dateformat is dd-mm-yy. I am a bit puzzled about date formats.

You need to reverse the logic by changing return [true, ''] and return [false, ''] to return [false, ''] and return [true, ''] respectively. You also need to remove minDate: ranges[0].start and maxDate: ranges[ranges.length -1].end

Here's a demo (I've changed the dates slightly to make it easier to see the effect. Just go forward to September 2016).

 var ranges = [ { start: new Date(2016, 8, 1), end: new Date(2016, 8, 20) }, { start: new Date(2016, 9, 1), end: new Date(2016, 9, 20) }, { start: new Date(2016, 10, 1), end: new Date(2016, 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 [false, '']; } return [true, '']; } }); }); 
 @import url(https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <input type="text" id="datepicker"> 

Edit

Just a quick edit here to address the date issue. Your date format is a non-standard d(d)-m(m)-yyyy . You can get it to a standard format pretty easily by converting it to an array, having the values [day,month,year] as numeric strings (eg ["4", "27", "2016"] for 27-4-2016 ). Here's a snippet to do that

// our date-like string and an array equivalent
var d = '27-4-2016',
    dArray = d.split('-');
// rearrange the month and day
dArray.splice(1, 0, dArray.shift());
// create a date object called date and pass our array to the constructor
var date = new Date(dArray); // Result: Wed Apr 27 2016 00:00:00 GMT-0500 (CDT)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM