【问题标题】:Set restriction for the datetime-local , only selecting the current date为 datetime-local 设置限制,只选择当前日期
【发布时间】:2021-09-14 20:57:30
【问题描述】:
我现在正在编写一个包含日期选择器的表单......并且我正在尝试使用该元素。现在,我想限制它只选择当前日期。
例如
今天是 7 月 7 日
所以日期选择器上的选择只有 7 月 7 日
有人可以帮我吗?我是网络应用程序的新手
<div class="form-group ">
<label class="font-weight-bold">Check in</label>
<input type="datetime-local" id="datefield">
</div>
<div class="form-group ">
<label class="font-weight-bold">Check Out</label>
<input type="datetime-local" id="CheckOut">
</div>
【问题讨论】:
-
请edit您的问题显示您所做的任何研究以及您为自己解决问题所做的任何尝试。例如,input 元素具有min 和max 属性,它们告诉控件最小值和最大值是什么。您认为这些如何适用于您的情况?
-
见MDN: Input type datetime-local。将 min 和 max 属性设置为适当的值,例如 ...min="2021-07-04T00:00" max="2021-07-04T23:59:59"...,以将选择限制在 2021 年 7 月 4 日的某个时间。
标签:
javascript
html
jquery
datetime
【解决方案1】:
<div class="form-group ">
<label class="font-weight-bold">Check in</label>
<input type="datetime-local" id="CheckIn" min="2021-07-07T00:00" max="2021-07-07T23:59" >
</div>
<div class="form-group ">
<label class="font-weight-bold">Check Out</label>
<input type="datetime-local" id="CheckOut" min="2021-07-07T00:00" max="2021-07-07T23:59">
</div>
或者,如果你想在“当天”使用它,你将需要一些 Javascript:
const today=(new Date()).toLocaleString("EN-CA").slice(0,10); // get local current date
document.querySelectorAll('input[type="datetime-local"]').forEach(el=>{
el.min=today+"T00:00"; el.max=today+"T23:59";
})
<div class="form-group ">
<label class="font-weight-bold">Check in</label>
<input type="datetime-local" id="CheckIn">
</div>
<div class="form-group ">
<label class="font-weight-bold">Check Out</label>
<input type="datetime-local" id="CheckOut">
</div>
我在这里使用 Date.prototype.toLocaleString() 而不是 Date.prototype.toISOString(),因为这将返回 locale 日期而不是 GMT 日期,这在一天中的某些时间可能会有所不同,具体取决于哪个时区用户在其中。区域设置“EN-CA”确保格式为“YYYY-MM-DD”。