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 >
<label for="startDate">Start</label>
<input id="startDate" 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?
CodePudding user response:
Try something like this:
window.onload = function () {
const myDate = document.getElementById("startDate");
const today = new Date();
myDate.value = today.toISOString().slice(0, 10);
};
CodePudding user response:
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
})