Noam B.
Noam B.

Reputation: 3250

Setting the value of input type month

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

Answers (5)

Vivek Maru
Vivek Maru

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

user4963716
user4963716

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"  >
you can use class also to do it

Upvotes: 1

0xdw
0xdw

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

Suresh Atta
Suresh Atta

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

Nirnae
Nirnae

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

Related Questions