问题
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?
回答1:
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">
回答2:
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">
回答3:
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" />
来源:https://stackoverflow.com/questions/53188184/how-to-set-a-default-month-in-an-input-element