I have the following html code to only accept date greater than or equal to the current date in vanilla javascript. However for some reason it does not seem to accept the minDate
value in the <script>
tag of the html file.
<body>
<form>
<td><label for="Ride_Start_Date">Ride Start Date</label></td>
<td><input type = "date" id="Ride_Start_Date" name="Ride_Start_Date"></td>
<td><button type="submit" >Submit Query</button></td>
</form>
<script>
var todayDate = new Date();
var month = todayDate.getMonth();
var year = todayDate.getUTCFullYear() - 0;
var tdate = todayDate.getDate();
if(month < 10){
month = "0" month
}
if(tdate < 10){
tdate = "0" tdate;
}
var minDate = year "-" month "-" tdate;
document.getElementById("Ride_Start_Date").setAttribute('min',minDate);
console.log(maxDate);
alert(" minDate=" minDate);
</script>
</body>
this does not work and doesn't limits the date input,
However when I use a hardcoded string while leaving everything else the same such as: document.getElementById("Ride_Start_Date").setAttribute('min',"2022-05-31");
this works perfectly.
I've tried looking at many answers but they all seem to work perfectly with a variable value for the setAttribute but mine does not. What do I seem to be doing wrong here?
Would appreciate any and all assistance in this
CodePudding user response:
You should use var month = todayDate.getMonth() //getMonth from 0 to 11 Today is 2022-05-31 You are trying to set 2022-04-31 as the minimum date. This is the wrong date. That's why it doesn't work