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.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.