Reputation: 3250
How do I set the value of input element type month with javascript?
<input type="month>
Couldn't find anything about that in the web.
Upvotes: 4
Views: 5603
Reputation: 8499
You can simply the code below to set the current month into your #month-input-element
.
let now = new Date();
let currentYear = now.getFullYear();
let currentMonth = ("0" + (now.getMonth() + 1)).slice(-2);
$('#month-input-element').val(`${currentYear}-${currentMonth}`);
Upvotes: 0
Reputation:
var month = document.getElementsByClassName('month');
for (i = 0; i < month.length; i++) {
month[i].value = '2017-06';
}
<input type="text" class="month" >
<input type="text" class="month" >
Upvotes: 1
Reputation: 3842
Your can set value as below,
const monthControl = document.querySelector('#month-control[type="month"]');
monthControl.value = '1978-06';
<input type="month" id="month-control">
Please consider the Browser compatibility
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari
Basic support | 20 | 12 | No support[1] | No support | 10.62 | No support[2]
Upvotes: 2
Reputation: 121998
You can use the value attribute like any other type
<input type="month" value="2017-09">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/month
If you are looking for JS solution, just like you set value to an input, you can do
document.getElementById("abc").value = "2017-09";
Notes:
1) While using it, there must be always year. This is a major annoying thing.
2)Be aware that there are browser issues with it.
However, there are issues with because at this time, many major browsers don't yet support it.
We'll look at basic and more complex uses of , then offer advice on mitigating the browser support issue in the section Handling browser support).
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/month#Handling_browser_support
Suggestion :
I personally don't like the way it is developed and designed in the current want docs supporting the same
The best way to deal with dates in forms in a cross-browser way (until all of the major browsers have supported them for a while) is to get the user to enter the month and year in separate controls ( elements being popular; see below for an implementation), or use JavaScript libraries such as the jQuery date picker plugin.
Upvotes: 4
Reputation: 1345
As Suresh said you can access and update it like any other type of input so :
<input type="month" id="month_input">
And in your JS :
document.getElementById("month_input").value = "2017-09";
Upvotes: 1