How to set a default month in an input element?

我怕爱的太早我们不能终老 提交于 2021-02-20 19:49:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!