You have to take into account that an input type="date"
accepts a string in the format aaaa-mm-dd
. This means that the month must be 01
and not only 1
.
If you put for example input.value = '2015-1-25';
it will not work.
Also notice that I use " -
" instead of " /
".
There is another recent way for modern browsers, .valueAsDate
that directly accepts a Date
object.
Using .value
:
var Hoje = new Date();
dia = Hoje.getDate();
mes = Hoje.getMonth() + 1;
ano = Hoje.getFullYear();
var data = [ano, mes, dia].map(function (nr) {
return (nr + '').length == 1 ? '0' + nr : nr;
});
document.querySelector('input[name="dia"]').value = data.join('-');
jsFiddle: link
In this line return (nr + '').length == 1 ? '0' + nr : nr;
together a zero in case the string only has 1 character. The idea of doing (nr + '')
is just to convert the number to string ("cast to string").
Using .valueAsDate
:
document.querySelector('input[name="dia"]').valueAsDate = new Date();
jsFiddle: link