How to Set a Default Value on "month" input HTML Element?

HTML <input> element with the type attribute set to "month" (i.e. <input type="month" />) accepts a value in "YYYY-MM" format only. It creates an input field that allows a user to enter a month and a year.

For example, to set the month to "June 2022", you would set the <input> value to "2022-06":

<input type="month" name="date_birth" value="2022-06" />

When the value of this form field is submitted to the server, it will be in "YYYY-MM" format as well (which, according to the example above, would be "date_birth=2022-06").

The value that's actually displayed in the browser might be different from the value added to 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 (i.e. the user-agent) chooses to display the value. Most user-agents display the month and year in a locale-appropriate form, based on the set locale of the user's operating system.

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.