我的<input type=date>
页面中有html
个字段。我试图在javascript
中创建一个函数,如果选择了比今天更大的日期,那么将在该字段中设置今天的日期。实际上,我想将最长日期限制在今天的日期。这是jsfiddle中的代码。我做错了什么?
HTML:
<div class="entry">
<label for="startDate">Start date:</label>
<input id="startDate" name="startDate" type="date" oninput="validDate(startDate)">
</div>
使用Javascript:
function validDate(date) {
todayDate = getTodaysDate();
if (date > todayDate)
document.searchForm["date"].value = todayDate;
}
function getTodaysDate(){
date = new Date();
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
today = year + "-" + month + "-" + day;
return today;
}
答案 0 :(得分:3)
您可以设置max属性以将其限制为今天的日期:
document.getElementById('startDate').setAttribute('max', getTodaysDate());
答案 1 :(得分:1)
这是一个适合我的更新小提琴(至少在Chrome / Windows中):
JavaScript的:
function validDate(date, theInput) {
var date = document.getElementById("startDate").value;
todayDate = getTodaysDate();
if (date > todayDate)
theInput.value = todayDate;
}
function getTodaysDate(){
date = new Date();
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
today = year + "-" + month + "-" + day;
return today;
}
HTML:
<div class="entry">
<label for="startDate">Start date:</label>
<input id="startDate" name="startDate" type="date" oninput="validDate(this.value, this)">
</div>