【问题标题】:Jquery ui datepicker preselect date that is not a sundayJquery ui datepicker预选不是星期天的日期
【发布时间】:2021-03-03 18:13:18
【问题描述】:

我已修改 jquery ui datepicker 以预先选择从现在起 2 天后的日期,并且我还在 datepicker 中禁用了星期日。但是,如果距现在 2 天是星期日,则输入字段仍会预填星期日。如何防止这种情况发生?

  $(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");
  });

【问题讨论】:

  • 如果是星期天,应该显示什么日期,星期六还是星期一?

标签: javascript jquery user-interface jquery-ui datepicker


【解决方案1】:

假设您将切换到第二天,星期一,您可以使用条件(三元)运算符。

这是一个例子。

$(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>

如果今天是星期五 (5),加上 2 天,将成为下周的星期日(7,或在 JS:0)。所以我们可以检查一下。

通常我们可能会创建一个函数:

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

然后像这样使用它:

minDate: pickDay(2),

我对此进行了测试,但不喜欢,似乎有一些时间问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 2012-03-24
    相关资源
    最近更新 更多