我想限制日期,以便用户不必选择少于一年的日期,但是我希望与系统日期相比它是自动完成的。如果有人有想法,我将不胜感激。
答案 0 :(得分:2)
您可以获取当前日期,并从当前年份中减去一年并设置disabled="false"
属性
min
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 minDate = (year-1) + '-' + month + '-' + day;
document.getElementById('dt').setAttribute('min', minDate);
答案 1 :(得分:0)
您可以为输入元素指定min
和max
属性:
let input = document.querySelector("#test");
let nextYear = new Date(new Date().setFullYear(new Date().getFullYear() + 1));
let today = new Date();
input.max = formatDate(nextYear)
input.min = formatDate(today)
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
<input type="date" id="test"/>