Displaying date in date field

2

I'm trying to display the date of the day in the date field:

<input type="date" name="dia" />.

Being the date I picked up via JS:

var Hoje = new Date();
var data;
Hoje.getDate();
Hoje.getDay();
Hoje.getMonth();
dia = Hoje.getDate();
mes = Hoje.getMonth()+1;
ano = Hoje.getFullYear();

 data = dia +'/'+ mes +'/'+ ano;
    
asked by anonymous 24.01.2015 / 03:03

1 answer

2

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

    
24.01.2015 / 09:21