Question:
I need javascript to automatically fill in an <input type="hidden" />
with the current date, and another with 15 days after the current date.
It will be used for the date of issue of a bank slip and the other for the expiration date of the bank slip, and I need the format to be aaaammdd
.
<input name="dataEmissao" type="hidden" />
<script>
????????????????
</script>
e
<input name="dataVencimentoTit" type="hidden" />
<script>
????????????????
</script>
Obs: it can't be PHP, because I'm using this code inside a code block of the theme, in WordPress. Inside there is no PHP code, only JavaScript.
Answer:
How to set a date in one input and another, fifteen days later in another?
The steps you need to follow are:
- create a date object with the start day
- create a new date object
1296e6
longer than the other (because JavaScript works in milliseconds) - have a function to format the output string, in this case
YYYYMMDD
- go to the DOM "fetch" the elements and set their
.value
In practice:
function pad(s) {
return (s < 10) ? '0' + s : s;
}
function formatarData(d) {
return [d.getFullYear(), d.getMonth() - 1, d.getDate()].map(pad).join('');
}
var emissao = document.querySelector('input[name="dataEmissao"]');
var vencimento = document.querySelector('input[name="dataVencimentoTit"]');
var hoje = new Date();
var quinzeDias = new Date(hoje.getTime() + 1296e6);
emissao.value = formatarData(hoje);
vencimento.value = formatarData(quinzeDias);