我有 2 个 jquery 日期选择器输入
我将默认设置设置为这样:
$("#polis_date_from").datepicker({
uiLibrary: "bootstrap4",
changeYear: true,
changeMonth: true,
dateFormat: "yy.mm.dd",
yearRange: "-0:+1"
});
$("#polis_date_to").datepicker({
uiLibrary: "bootstrap4",
changeYear: true,
changeMonth: true,
dateFormat: "yy.mm.dd",
maxDate: "+365d"
});
$("#polis_date_from").datepicker("setDate", new Date());
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/theme.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<input id="polis_date_from" placeholder="YYYY.mm.dd" />
<input id="polis_date_to" placeholder="YYYY.mm.dd" />
但问题是人们可以更改“polis_date_from”日期选择器中的日期,例如: 2024.09.09 . 第二个日期选择器“#polis_date_to”仍然具有从今天开始的 maxRange + 365d。 如何动态更改 maxDate 使其始终距“polis_date_from”中的日期+365d?
我尝试写这个,但没有成功:
$("#polis_date_from").on("change", async function (e) {
var today = new Date().getTime();
var polis_date_from_date = new Date($("#polis_date_from").val()).getTime();
var timeDiff = Math.abs(polis_date_from_date - today)
var daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))
$("#polis_date_to").datepicker({
maxDate: `+${365 + daysDiff}d`
});
})
当用户在
#polis_date_from
日期选择器上选择日期时,获取该日期并为其添加年份。并将此值设置为您的 maxDate
日期选择器上的 #polis_date_to
。请参阅以下示例。
$("#polis_date_from").datepicker({
uiLibrary: "bootstrap4",
changeYear: true,
changeMonth: true,
dateFormat: "yy.mm.dd",
yearRange: "-0:+1",
onSelect: function() {
var maxDate = $('#polis_date_from').datepicker('getDate');
maxDate.setFullYear(maxDate.getFullYear() + 1);
$("#polis_date_to").datepicker("change", {
maxDate: maxDate
});
}
});
$("#polis_date_to").datepicker({
uiLibrary: "bootstrap4",
changeYear: true,
changeMonth: true,
dateFormat: "yy.mm.dd",
maxDate: "+365d"
});
$("#polis_date_from").datepicker("setDate", new Date());
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/theme.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<input id="polis_date_from" placeholder="YYYY.mm.dd" />
<input id="polis_date_to" placeholder="YYYY.mm.dd" />