[英]bootstrap 5 datepicker set as default current date and dont let set a past one
I found and refactor this code to use a datepicker with bootstrap 5, now i want to set as default the current date but I can't figure how to do that.我发现并重构了这段代码以使用带有 bootstrap 5 的日期选择器,现在我想将当前日期设置为默认日期,但我不知道该怎么做。
this is my code:这是我的代码:
<div class="form-group">
<label for="startDate">Start</label>
<input id="startDate" class="form-control" type="date" />
</div>
and the script to handle it和处理它的脚本
<script>
let startDate = document.getElementById('startDate')
let endDate = document.getElementById('endDate')
startDate.addEventListener('change',(e)=>{
let startDateVal = e.target.value
document.getElementById('startDateSelected').innerText = startDateVal
})
endDate.addEventListener('change',(e)=>{
let endDateVal = e.target.value
document.getElementById('endDateSelected').innerText = endDateVal
})
</script>
how could I set as default the current date and also don't let user to pick a past date as today?我如何将当前日期设置为默认日期,并且不让用户选择过去的日期作为今天?
Try something like this:尝试这样的事情:
window.onload = function () {
const myDate = document.getElementById("startDate");
const today = new Date();
myDate.value = today.toISOString().slice(0, 10);
};
let startDate = document.getElementById('startDate')
startDate.addEventListener('change',(e)=>{
let startDateVal = e.target.value // returns the date in this format "2022-12-07" (YYYY-MM-DD)
// You can use new Date() and set the datepicker-value as the argument
// You can compare Date objects
// new Date() gives you a Date object with this exact moment in time
// the isBeforeThisMoment variable will hold a boolean telling if the value is before this exact moment
const isBeforeThisMoment = new Date(startDateVal) < new Date()
// Checks if it is before this moment, if it is, set the value of the datepicker to an empty string
if(isBeforeThisMoment) startDate.value = ""
// The datepicker should now indicate that no date has been picked
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.