How to Set Value of HTML "month" input Element Using JavaScript?

Adding a value to HTML input element with type set to "month"

The HTML <input type="month"> element expects the value attribute to be set in "YYYY-MM" format. Therefore, if you're setting its value using JavaScript, you must adhere to the correct format.

For example, let's suppose you have the following <input> field:

<input id="birthday" type="month" name="date_birth" />

To set its value using JavaScript, you would do the following:

const monthField = document.getElementById('birthday');
monthField.value = '2022-06';

This would set the value of the <input type="month"> element to "2022-06".

Please note that the value that's actually displayed in the browser might be different from the value set on the <input type="month" /> field (depending on the browser and/or the operating system the user is using). For example, a value set to "2022-06" might be shown to the user as "June 2022" in the browser. This depends on how the browser/user-agent chooses to display the value.

Before you use the <input type="month"> element, please make sure that you're aware of the browser support.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.