Bootstrap Datepicker plugin disable past dates

Bootstrap’s own plugins, datepicker provides a data-api that can be used to instantiate datepickers without the need for custom JavaScript. You can simply set data-provide=”datepicker” on the element you want to initialize, and it will be initialized with that element. It is really easy and simple bootstrap’s own built-in plugin.

You need not write custom JavaScript code for datepicker, just simply add the bootstrap library and initialize the element you want.

Here, I am gonna to tell you how to show date picker and disable the past dates from pick up.

Add Bootstrap datepicker CSS & JS file:

First, you need to add bootstrap’s own datepicker CSS & JS plugin. Below is the CDN you can use:

// Add inside your template head section
https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css

// Add at the bottom of your template section before closing body
https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js

Note: Do not forget to add JQuery, bootstrap’s main CSS & JS plugin.

How to use with element

You can use any element you want to initialize like div, span, etc. Here, I am going to use div.

// datepicker is the element used to initialize date

<div id="datepicker" class="date" data-date-form="mm-dd-yyyy">
    <input type="text" readonly/>
</div>

Trigger datepicker

Now you need to trigger the datepicker function.

<script type="text/javascript">
     $(document).ready(function() {
          var date = new Date();
          date.setDate(date.getDate());  // get current date
          $( "#datepicker" ).datepicker({
               startDate: date  //initialize current date atlease
          });
     });
</script>

startDate: is initialized with the current date, it means you need to input current or upcoming date only, it will disable datepicker’s past date.

Comments

Be the first to comment