带有手动输入和动态最小日期的jQuery UI datepicker

时间:2019-03-18 14:40:39

标签: jquery jquery-ui jquery-ui-datepicker

我的页面上有几个日期选择器,可以通过选择器或手动输入来填充。这些日期选择器应遵循一些规则,但我不知道如何动态解决。

  问题1
  日期2不应早于日期1。日期3不应早于1和2。
  目前,此功能适用于日期选择器,但不适用于手动输入。如果手动输入日期且该日期早于最小日期,则该字段应留空。

  问题2
  如果第一个日期更改(更改为以前的较早日期),则第二个日期的最小日期也应更新。
  第三日期选择器也是如此。

该页面上可能有1-x日期选择器!

let d = new Date();
let nextValidDate = d.getDate() + "." + (d.getMonth() + 1) + "." + d.getFullYear();

$(document).on("blur change", ".datepicker", function () {
    nextValidDate = $(this).datepicker("getDate");
});

$(document).on('focus', '.datepicker',
    function () {
        $(this).datepicker({
            numberOfMonths: 1,
            firstDay: 1,
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd.mm.yy',
            minDate: nextValidDate
        });

        $(this).datepicker('show');
    });


$(document).on('blur', '.datepicker', function () {
    if ($(this).val().length >= 2) {
        parseInputDate(this);
    }
});



function parseInputDate(elm) {
    var currDate = new Date(),
        monDt = (('0' + currDate.getMonth() + 1).slice(-2) + ('0' + currDate.getDate()).slice(-2)), // get current month+date to compare
        inputVal = $(elm).val().match(/\d{2}/gi); // split date components into array of [dd,mm,yy,yy]

    // another date validation, by comparing parameters and date object result 
    var isValidDate = function (yyyy, mm, dd) {
        var dt = new Date(yyyy, parseInt(mm, 10) - 1, dd);
        return (dt.getFullYear() + '-' + ('0' + (dt.getMonth() + 1)).slice(-2) + '-' + ('0' + dt.getDate()).slice(-2)) == yyyy + '-' + mm + '-' + dd;
    }

    if (inputVal != null && inputVal.length >= 2) {
        var year = currDate.getFullYear();

        if (monDt > (inputVal[1] + inputVal[0])) year++;
        // generate formatted text based on date component count
        // add date validation to catch invalid dates using (new Date('yyyy-mm-dd')).getTime() which will return NaN on invalid date

        var result = (inputVal.length == 2 && isValidDate(year, inputVal[1], inputVal[0]) && inputVal[0] + '.' + inputVal[1] + '.' + year) ||
            (inputVal.length == 3 && isValidDate('20' + inputVal[2], inputVal[1], inputVal[0]) && inputVal[0] + '.' + inputVal[1] + '.20' + inputVal[2]) ||
            (inputVal.length == 4 && isValidDate(inputVal[2] + inputVal[3], inputVal[1], inputVal[0]) && inputVal[0] + '.' + inputVal[1] + '.' + inputVal[2] + inputVal[3]) ||
            ''; // set empty on invalid dates

        $(elm).val(result);
        nextValidDate = result;
    } else {
        $(elm).val('')
    };
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

<div>
  <label for="date1">Date 1:</label>
  <input type="text" class="datepicker" id="date1">
</div>
<div>
  <label for="date2">Date 2:</label>
  <input type="text" class="datepicker" id="date2">
</div>
<div>
  <label for="date3">Date 3:</label>
  <input type="text" class="datepicker" id="date3">
</div>

1 个答案:

答案 0 :(得分:1)

考虑以下示例:http://jqueryui.com/datepicker/#date-range

我们可以这样设置您的代码:

$(function() {
  var dateFormat = 'dd.mm.yy';

  function getDate(el) {
    var date;
    try {
      date = $.datepicker.parseDate(dateFormat, el.value);
    } catch (error) {
      date = null;
    }
    return date;
  }

  function checkMinDate(el) {
    var date = getDate(el);
    var minDate = $(el).datepicker("option", "minDate");
    var test;
    try {
      test = (date >= minDate);
    } catch (error) {
      test = false;
    }
    return test;
  }

  $(".datepicker").datepicker({
    numberOfMonths: 1,
    firstDay: 1,
    changeMonth: true,
    changeYear: true,
    dateFormat: dateFormat,
    minDate: 0
  }).on("change", function(e) {
    e.preventDefault();
    var td = getDate(this);
    var dpid = $(this).attr("id");
    var dpi = parseInt(dpid.slice(dpid.indexOf("-") + 1));
    $("#date-" + (dpi + 1)).prop("disabled", false).datepicker("option", {
      minDate: td,
      defaultDate: td
    });
    if (!checkMinDate(this)) {
      this.value = "";
      return false;
    }
    return true;
  });
  $(".datepicker:not(:eq(0))").prop("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<div class="date-wrapper">
  <div>
    <label for="date1">Date 1:</label>
    <input type="text" class="datepicker" id="date-1">
  </div>
  <div>
    <label for="date2">Date 2:</label>
    <input type="text" class="datepicker" id="date-2">
  </div>
  <div>
    <label for="date3">Date 3:</label>
    <input type="text" class="datepicker" id="date-3">
  </div>
  <div>
    <label for="date3">Date 4:</label>
    <input type="text" class="datepicker" id="date-4">
  </div>
  <div>
    <label for="date3">Date 5:</label>
    <input type="text" class="datepicker" id="date-5">
  </div>
</div>

我相信这符合您的条件:

  • 以前的日期字段应小于或“在”当前日期字段之前。
  • 所有以前的日期应小于此日期字段。
  • 如果日期更改,则以下日期的最小日期也应更新。

函数getDate()接收一个元素,并检测它是否包含String格式的日期(基于日期格式),并返回一个等于该日期或null的Date对象。

功能checkMinDate()是为了帮助我们检测手动输入日期。它将对照minDate值检查手动输入的日期。如果它大于或等于minDate,它将返回true。如果小于minDate,它将返回false。

在我们的change回调中,我们使用.preventDefault()停止当前操作。这对于我们要测试输入内容的类型事件很有用。我们稍后可以返回truefalse来允许事件进行。如果checkMinDate不为真,我们可以清除该值并返回false。

希望有帮助!

相关问题