javascript HTML5 日期选择器防止过去的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21396605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 datepicker prevent past dates
提问by Rahul Desai
I am working on a website for booking movie tickets. What should I set the min
attribute to, to prevent past dates in the HTML5 datepicker? (I do not want to use PHP solution mentioned here.)
我正在开发一个用于预订电影票的网站。我应该将min
属性设置为什么,以防止 HTML5 日期选择器中的过去日期?(我不想使用这里提到的 PHP 解决方案。)
Is there a pure HTML5/Javascript solution for this?
是否有纯 HTML5/Javascript 解决方案?
回答by atxpunkrock
When the document loads have the date input disabled. Run an onload
function that inserts today's date into the min field in the required format.
当文档加载时禁用日期输入。运行一个onload
函数,以所需的格式将今天的日期插入到 min 字段中。
function onLoad() {
var input = document.getElementById("dateField");
var today = new Date();
// Set month and day to string to add leading 0
var day = new String(today.getDate());
var mon = new String(today.getMonth()+1); //January is 0!
var yr = today.getFullYear();
if(day.length < 2) { day = "0" + day; }
if(mon.length < 2) { mon = "0" + mon; }
var date = new String( yr + '-' + mon + '-' + day );
input.disabled = false;
input.setAttribute('min', date);
}
document.addEventListener('load', onLoad, false);
<body>
<input id="dateField" type="date" disabled />
</body>
Here it is in a fiddle: http://jsfiddle.net/tj9Xh/2/
这是一个小提琴:http: //jsfiddle.net/tj9Xh/2/
回答by Savaratkar
try this:
试试这个:
<input id="dateField" type="date"/>
var dt= new Date();
var yyyy = dt.getFullYear().toString();
var mm = (dt.getMonth()+1).toString(); // getMonth() is zero-based
var dd = dt.getDate().toString();
var min = yyyy +'-'+ (mm[1]?mm:"0"+mm[0]) +'-'+ (dd[1]?dd:"0"+dd[0]); // padding
alert(min);
$('#dateField').prop('min',min);