You have to take into account that an input type="date"
accepts a string in format aaaa-mm-dd
. That means the month must be 01
and not only 1
.
If you put for example input.value = '2015-1-25';
won’t work.
Notice also what I use "-
" in time of "/
".
There is another recent amis way, for modern browsers, the .valueAsDate
that directly accepts an object Date
.
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('-');
In this line return (nr + '').length == 1 ? '0' + nr : nr;
add a zero in the case of a string only have 1 character. The idea to make (nr + '')
is just to convert the number into string ("cast to string").
Using .valueAsDate
:
document.querySelector('input[name="dia"]').valueAsDate = new Date();
And what’s the problem? There’s some mistake?
– André Ribeiro