0

I have the following Jquery ui datepicker setup. I want to highlight a specific date in the future, how can that be done?

I already have weekends disabled so that's adding extra complications using beforeShowDay.

    $('#mypicker').datepicker({
        //options
        minDate: now,
        firstDay: 0,
        format: "yyyy.mm.dd",
        onSelect: function(dateText, inst) {
            $('.new_ship_date').val(dateText);
        },
        beforeShowDay: $.datepicker.noWeekends,

    });

This is the answer in another question but I can't work out how to combine that with the disable weekends function.

var your_dates = [new Date(2011, 7, 7),new Date(2011, 7, 8)]; // just some dates.

$('#whatever').datepicker({
   beforeShowDay: function(date) {
      // check if date is in your array of dates
      if($.inArray(date, your_dates)) {
         // if it is return the following.
         return [true, 'css-class-to-highlight', 'tooltip text'];
      } else {
         // default
         return [true, '', ''];
      }
   }
});
Rob
  • 6,304
  • 24
  • 83
  • 189

1 Answers1

0

To combine the $.datepicker.noWeekends function in to your logic to highlight cells based on the date in the array, you can call the noWeekends() function separately to determine if the date is a weekend. You can then use that value in the check to see if the date matches one of those in your array and return the weekend flag in the first element of the array.

Try this:

let now = new Date();

// just for testing:
let addDays = (date, days) => {
  let newDate = new Date(date);
  newDate.setDate(date.getDate() + days);
  return new Date(newDate.toDateString());
}

// map() is used here to store dates as epochs to make comparison easier later on
var highlightDates = [addDays(now, 1), addDays(now, 2), addDays(now, 3)].map(Number); 

$('#mypicker').datepicker({
  minDate: now,
  firstDay: 0,
  format: "yyyy.mm.dd",
  onSelect: function(dateText, inst) {
    $('.new_ship_date').val(dateText);
  },
  beforeShowDay: function(date) {
    let isWeekday = $.datepicker.noWeekends(date)[0];
    if (highlightDates.indexOf(+date) != -1) {
      return [isWeekday, 'highlight', 'tooltip text'];
    } else {
      return [isWeekday, '', ''];
    }
  }
});
.highlight a.ui-state-default {
  background-color: #C00;
  color: #FFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />

<input type="text" id="mypicker" />
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Ok thanks will give it a go. Can I also simplify slightly and just highlight one specific date just by changing this `var highlightDates = [addDays(2021, 03, 03)].map(Number);`? – Rob Jan 20 '21 at 13:47