Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pre-populating date input field with Javascript

I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:

<html>
...
<input id='date' type='date'>
...
</html>

<script>
...
var myDate = new Date();
$("#date").val(myDate);
...

I have also tried passing the date object as a string

var myDate = new Date().toDateString();
$("#date").val(myDate);

When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.

Thanks.

like image 232
MyTimeFinder Avatar asked Sep 06 '25 10:09

MyTimeFinder


1 Answers

It must be set in ISO-format.

(function () {
    var date = new Date().toISOString().substring(0, 10),
        field = document.querySelector('#date');
    field.value = date;
    console.log(field.value);

})()

http://jsfiddle.net/GZ46K/

like image 146
Robin Drexler Avatar answered Sep 08 '25 01:09

Robin Drexler