Blog

This tutorial will teach you how to add a date picker to your form using open source tools. A date picker is an interactive dropdown that makes it easy to choose the date from a calendar instead of typing it manually. It's a great way to avoid user errors because you can see the corresponding day of the week for each date. Plus it gives your form a little extra interactive shine!

Bootstrap-Datepicker Plugin

We'll be using the Bootstrap-Datepicker plugin to handle all the dirty work. There are a number of date picker options out there, but Bootstrap-Datepicker is one of the most popular and full-featured libraries available. However, if instead of a single date, you want a date picker to extend across a range of dates, you might consider this option.

The .container-fluid, .row, and .col-md-6 .col-sm-6 .col-xs-12 divs are part of the Bootstrap grid system that will make the form's width responsive to a variety of different devices.

All of the Bootstrap code is wrapped in a .bootstrap-iso div which tells the bootstrap-iso.css file that we want to use Bootstrap styling within the div. If you are already using Bootstrap CSS on your website, you can omit this div.

Notice that I have given the input an id and name of date. This is a unique identifier that we will need to provide to the datepicker plugin.

Step 3: Setup and Initialize Datepicker Plugin

All that is left to do is to write a snippet of JavaScript to tell the datepicker plugin where to find the date input and how to handle it.

First, we use jQuery to wait until the page elements have finished loading. Then, we select the date<input>.

If the user is using our isolated version of Bootstrap, we select the container div `.bootstrap-iso'. This way we can tell the date picker to append the interactive element within the div where Bootstrap CSS is being applied.

There are a number of possible plugin options described in the documentation. For our purposes, we specify the format of the date, define a container element, highlight today's date, and close the interactive popup after a date has been chosen. All that, all that is left is to initialize the plugin.