Back to Snippets

Custom Date Picker JS

Click the field and a calendar drops down for the current month. Step through months with the arrows, pick a day and the field fills with the date, or press Escape to close without choosing.

The calendar is rebuilt every time the month changes. The script works out which weekday the month starts on and how many days it has, pads the front of the grid with blank cells and renders one button per day, so every date is a real focusable control. Month and weekday names come from Intl.DateTimeFormat, so the picker reads correctly in whatever language the browser is set to. The chosen date goes into the input as a readable string and into a data attribute in ISO format for a form to submit.

Clicking outside the picker closes it through one listener on the document, and the field is readonly so a phone keyboard does not pop up over the calendar.

1
#javascript
#css
#date picker
#calendar
#form
#input
#ui