两个datepickers jQuery的限制日期

时间:2016-10-28 10:25:58

标签: javascript jquery date datepicker

我有一个问题,即使在谷歌搜索10个小时左右之后我似乎无法得到答案。所以,亲爱的朋友们;

我有两个完美合作的日期选择器,但我需要的最后一件事是最后一个日期选择器中的限制日期范围。限制日期应该是您在第一个日期选择器中选择之日起的14天。我已经尝试过maxDate,但它只限制了今天和未来14天的日期,但我想要的是限制它从所选择的第一个日期开始,然后在该日期之后的14天内限制它。这是我的代码:

HTML:

<input type="text" name="when" class="input-date" id="calendarfrom"/>
<input type="text" name="when" class="input-date" id="calendarto"/>

JS:

$(document).ready(function () {
    $("#calendarfrom").datepicker({
        dateFormat: "dd/mm/yy",
        minDate: 0,
        monthNames: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
        dayNamesMin: ['Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'],
        firstDay: 1,
        onClose: function (selectedDate) {
            $("#calendarto").datepicker("option", "minDate", selectedDate);
        }
    });
    $("#calendarto").datepicker({
        dateFormat: "dd/mm/yy",
        monthNames: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
        dayNamesMin: ['Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'],
        firstDay: 1,
        onClose: function (selectedDate) {
            $("#calendarfrom").datepicker("option", "maxDate", selectedDate);
        }
    });
});

1 个答案:

答案 0 :(得分:0)

选择日期后,您需要将日期添加到所选日期,然后使用maxDate

来自datepicker的

onClose

JSFIDDLE https://jsfiddle.net/tejashsoni111/a9a6jjkv/1/

$(document).ready(function () {
    $("#calendarfrom").datepicker({
        dateFormat: "dd/mm/yy",
        minDate: 0,
        monthNames: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
        dayNamesMin: ['Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'],
        firstDay: 1,
        onClose: function (date) {
            var dateParts = date.split("/");
            var dateObject = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
            var selectedDate = new Date(dateObject);
            var numberOfDaysToAdd = 14;
            var endDate = new Date(selectedDate);
            endDate.setDate(endDate.getDate() + numberOfDaysToAdd);
            $("#calendarto").datepicker("option", "minDate", selectedDate);
            $("#calendarto").datepicker("option", "maxDate", endDate);
        }
    });
    $("#calendarto").datepicker({
        dateFormat: "dd/mm/yy",
        monthNames: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
        dayNamesMin: ['Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'],
        firstDay: 1,
        onClose: function (selectedDate) {
            $("#calendarfrom").datepicker("option", "maxDate", selectedDate);
        }
    });
});

您可以在以下位置查看更多说明: Restrict date in jquery datepicker based on another datepicker or textbox