javascript bootstrap 5 datepicker设置为默认当前日期且不允许设置过去日期

0ve6wy6x  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(215)

我发现并重构了这段代码,以使用bootstrap 5的日期选择器,现在我想设置为默认的当前日期,但我不知道如何做到这一点。
这是我的代码:

<div class="form-group">
  <label for="startDate">Start</label>
  <input id="startDate" class="form-control" type="date" />
</div>

以及处理它的脚本

<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>

我怎么能设置为默认的当前日期,也不让用户选择过去的日期作为今天?

p8ekf7hl

p8ekf7hl1#

试试这样的方法:

window.onload = function () {
  const myDate = document.getElementById("startDate");
  const today = new Date();
  myDate.value = today.toISOString().slice(0, 10);
};
8xiog9wr

8xiog9wr2#

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
 })

相关问题