Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

min Attribute for date input type not accepting variable value in javascript

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" class="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");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading