Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default month in an input element?

Tags:

html

angular

Say I have an input element like this:

<input type="month">

How can I set the default value of this input element to the current month?

like image 207
P Rane Avatar asked Nov 07 '18 11:11

P Rane


People also ask

How do I select just the month in HTML?

The <input type="month"> defines a month and year control. The format is "YYYY-MM".

How do you write the input type for a date?

<input type="date"> <input> elements of type="date" create input fields that let the user enter a date, either with a textbox that validates the input or a special date picker interface.


2 Answers

You have to construct new Date and query your input, then do something like:

let date = new Date();
let month = `${date.getMonth() + 1}`.padStart(0, 2);
let year = date.getFullYear();
document.getElementById("month").value = `${year}-${month}`
<input id="month" type="month" value="2012-3-23">
like image 26
HynekS Avatar answered Sep 22 '22 02:09

HynekS


You may use some javascript:

const monthControl = document.querySelector('input[type="month"]');
const date= new Date()
const month=("0" + (date.getMonth() + 1)).slice(-2)
const year=date.getFullYear()
monthControl.value = `${year}-${month}`;
<input type="month">
like image 79
Smollet777 Avatar answered Sep 21 '22 02:09

Smollet777