如何使用输入类型日期动态只允许从当前日期算起一年? [英] How can I use input type date to dynamically only allow for one year from current date?
问题描述
到目前为止,这是我的代码.除了在输入标签本身中设置之外,我不知道如何完成最大日期.我希望它是动态的,所以无论当前日期是什么,日历只允许最多选择一年.
Here is my code so far. I am not sure how to accomplish a max date other than setting that in the input tag itself. I want it to be dynamic so whatever the current date is, the calendar only allows a selection of up to one year.
<input type="date" id="txtDate" />
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = dtToday + 365;
alert(maxDate);
$('#txtDate').attr('max', maxDate);
});
例如:今天是 10/1/2019 应该只允许选择日期为 10/1/2019-10/1/2020 明天应该允许用户只选择 10/2/2019-10/2/2020小提琴链接
example: today is 10/1/2019 it should be allowed to only select dated from 10/1/2019-10/1/2020 tomorrow a user should be allowed to only select from 10/2/2019-10/2/2020 link to fiddle
推荐答案
可以在页面加载时根据今天的日期设置日期输入的最小值和最大值:
Setting the min and max values for a date input based on today's date can be done when the page loads:
// Formt date as YYYY-MM-DD
function formatISOLocal(d) {
let z = n => ('0' + n).slice(-2);
return d.getFullYear()+'-'+z(d.getMonth()+1) + '-' + z(d.getDate());
}
window.onload = function() {
let inp = document.querySelector('#i0');
let d = new Date();
inp.min = formatISOLocal(d);
inp.defaultValue = inp.min;
d.setFullYear(d.getFullYear() + 1);
inp.max = formatISOLocal(d);
// Debug
console.log(inp.outerHTML);
}
<input type="date" id="i0">
如果用户代理不支持输入类型日期,这仍将设置最小/最大/默认值,但您必须自己处理超出范围的值.
If the user agent doesn't support input type date, this will still set the min/max/default values, but you'll have to handle out of range values yourself.
这篇关于如何使用输入类型日期动态只允许从当前日期算起一年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!