Displaying the date in the date field

Asked

Viewed 432 times

2

I’m trying to display the day’s date in the field date:

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

Being that 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;
  • And what’s the problem? There’s some mistake?

1 answer

2


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('-');

jsFiddle: http://jsfiddle.net/7m8a6yfw/

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();

jsFiddle: http://jsfiddle.net/fdfuzon5/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.