Home > Blockchain >  HTML input date field, how to set default value to today's date?
HTML input date field, how to set default value to today's date?

Time:04-21

I'm slightly confused as to why my JS script isn't working, I have set it up to populate the date field to today's date, but the HTML date picker is still showing dd/mm/yyyy by default.

my HTML is:

<div >
        <label for="date">Date</label>
        <input type="date" onl oad="getDate()"  id="date" name="date">
</div>

my JS is:

function getDate(){
var today = new Date();

document.getElementById("date").value = today.getFullYear()   '-'   ('0'   (today.getMonth()   1)).slice(-2)   '-'   ('0'   today.getDate()).slice(-2);

}

function getDate(){
var today = new Date();

document.getElementById("date").value = today.getFullYear()   '-'   ('0'   (today.getMonth()   1)).slice(-2)   '-'   ('0'   today.getDate()).slice(-2);

}
 <div >
           <label for="date">Date</label>
           <input type="date" onl oad="getDate()"  id="date" name="date">
 </div>

CodePudding user response:

I had some problems with that as well. I arrived at:

document.getElementById('mydate').value = new Date().toISOString().substring(0, 10);

CodePudding user response:

For input elements, the onl oad attribute is only supported when <input type="image">

Tip: You use DOMContentLoaded for setting the default value

<script>
    window.addEventListener('DOMContentLoaded', (event) => {
        document.getElementById("date").valueAsDate = new Date();
    });
</script>

Reference: https://www.w3schools.com/tags/att_onload.asp

  • Related