How to Create Month Input in HTML: Simple Guide
To create a month input in HTML, use the
<input type="month"> element. This input lets users select a year and month without a specific day, showing a calendar picker in supporting browsers.Syntax
The <input type="month"> element creates a control for selecting a month and year. You can add attributes like name, id, min, max, and value to control its behavior.
- type="month": Specifies the input is for month and year.
- name: Identifies the input in forms.
- min: Sets the earliest month selectable (format: YYYY-MM).
- max: Sets the latest month selectable.
- value: Sets the default selected month.
html
<input type="month" name="month" id="month" min="2020-01" max="2030-12" value="2024-06">
Output
A month picker input field showing June 2024 selected by default.
Example
This example shows a simple form with a month input. The user can pick a month and year, and the selected value is submitted.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Month Input Example</title> </head> <body> <form> <label for="month">Select a month:</label> <input type="month" id="month" name="month" value="2024-06" min="2020-01" max="2030-12"> <button type="submit">Submit</button> </form> </body> </html>
Output
A webpage with a labeled month input showing June 2024 selected and a submit button.
Common Pitfalls
Some common mistakes when using type="month" include:
- Using an invalid
valueformat (must beYYYY-MM). - Not setting
minandmaxproperly, which can confuse users. - Expecting day selection; this input only allows month and year.
- Browser support varies; some older browsers may not show a picker.
Always validate the input value on the server side as well.
html
<!-- Wrong value format --> <input type="month" value="06-2024"> <!-- Correct value format --> <input type="month" value="2024-06">
Output
The first input may not show the selected month correctly; the second input shows June 2024 selected.
Quick Reference
| Attribute | Description | Example |
|---|---|---|
| type | Defines input as month picker | month |
| name | Name for form submission | month |
| id | Unique identifier | month |
| value | Default selected month (YYYY-MM) | 2024-06 |
| min | Minimum selectable month | 2020-01 |
| max | Maximum selectable month | 2030-12 |
Key Takeaways
Use to let users pick a year and month easily.
The value format must be YYYY-MM, not MM-YYYY or other variations.
Set min and max attributes to limit selectable months if needed.
This input does not allow day selection, only month and year.
Check browser support and validate input on the server side.