Reputation: 306
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?
Upvotes: 6
Views: 6555
Reputation: 16691
To set the value for the month input (input[type="month"]
) use only the year and month in the value (yyyy-MM
), for example:
<input type="month" id="txtMonth" value="2018-11" />
will display the month as Novermber (in browsers that support month input type, support is patchy).
To populate the field using javascript could do something like:
var txtMonth = document.getElementById('txtMonth');
var date = new Date();
var month = "0" + (date.getMonth() + 1);
txtMonth.value = (date.getFullYear() + "-" + (month.slice(-2)));
<input type="month" id="txtMonth" value="2018-11" />
Upvotes: 2
Reputation: 3307
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">
Upvotes: 2
Reputation: 1646
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">
Upvotes: 9