Jquery ui datepicker preselect date that is not a sunday

帅比萌擦擦* 提交于 2021-02-11 15:11:38

问题


I have modified the jquery ui datepicker to pre-select the day that is 2 days from now and I have also disabled Sundays in the datepicker. However, the input field is still being pre-filled with the Sunday if the Sunday is 2 days from now. How do I prevent this?

  $(function() {
    $("#delivery-date").datepicker({
      minDate: +2, 
      maxDate: '+2M',
      dateFormat: "DD, d MM yy",
      showOn: "both",
      buttonText: "Change",
      beforeShowDay: function(date) {
        var day = date.getDay();
        return [(day != 0),  ''];
      }

    }).datepicker("setDate", "0");
  });

回答1:


Assuming you would switch to the Next day, Monday, you can use conditional (ternary) operator.

Here is an example.

$(function() {
  $("#delivery-date").datepicker({
    minDate: new Date().getDay() + 2 == 7 ? 3 : 2,
    maxDate: '+2M',
    dateFormat: "DD, d MM yy",
    showOn: "both",
    buttonText: "Change",
    beforeShowDay: function(date) {
      var day = date.getDay();
      return [(day != 0), ''];
    }
  }).datepicker("setDate", "0");
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p>Date: <input type="text" id="delivery-date"></p>

If today is Friday (5), adding 2 days, would make it Sunday of the next week (7, or in JS: 0). So we can check for that.

Normally we might make a function:

function pickDay(n){
  var d = new Date().getDay();  // Returns the day of the week: 5
  if(d + n == 7){
    return n + 1;
  }
  return n;
}

and then use it like so:

minDate: pickDay(2),

I tested this and it's not liked, there seems to be some timing issue.



来源:https://stackoverflow.com/questions/64927606/jquery-ui-datepicker-preselect-date-that-is-not-a-sunday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!