【发布时间】:2019-08-08 23:18:38
【问题描述】:
我的页面上有一些日期选择器,可以通过选择器或手动输入来填充。有一些规则应该适用于这些日期选择器,但我不知道如何动态解决这个问题。
问题 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>
【问题讨论】:
标签: jquery jquery-ui jquery-ui-datepicker