简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM