Comprehensive Guide to Using Bootstrap Datepicker with Events

8 Aug

In modern web development, integrating a date picker into your forms can significantly enhance the user experience. Bootstrap Datepicker is a popular choice due to its ease of use and compatibility with many admin themes built with Bootstrap. This guide will walk you through implementing a Bootstrap Datepicker with the changeDate event, ensuring your date picker is both functional and interactive.

Why Use Bootstrap Datepicker?

Bootstrap Datepicker is favored for several reasons:

  • Ease of Use: It integrates seamlessly with Bootstrap, a widely-used front-end framework.
  • Customizability: It offers various options to tailor the date picker to your specific needs.
  • Event Handling: It provides events like changeDate to handle user interactions efficiently.

Setting Up Bootstrap Datepicker

First, ensure you have the necessary Bootstrap and Datepicker libraries included in your project. You can include these via CDN for convenience or download them to host locally.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Bootstrap Datepicker Example</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
</head>
<body>
  <div class="container">
    <h2 class="mt-5">Bootstrap Datepicker Example</h2>
    <div id="datepicker" class="input-group date" data-provide="datepicker">
      <input type="text" class="form-control">
      <div class="input-group-addon">
        <span class="glyphicon glyphicon-th"></span>
      </div>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
</body>
</html>

Configuring the Datepicker

With the basic setup in place, you can now initialize the datepicker and customize its options. The following example demonstrates how to enable autoclose, set the date format, and restrict the selectable date range.

$(document).ready(function(){
  $('#datepicker').datepicker({
    autoclose: true,
    format: 'dd-mm-yyyy',
    startDate: '-3d'
  }).on("changeDate", function(e) {
    var day = e.date.getDate();
    var month = e.date.getMonth() + 1;
    var year = e.date.getFullYear();

    if(month < 10) {
      month = "0" + month;
    }

    var fullDate = year + "-" + month + "-" + day;
    console.log("Selected date: " + fullDate);
  });
});

In this example:

  • autoclose: true ensures the datepicker closes automatically after selecting a date.
  • format: 'dd-mm-yyyy' specifies the date format.
  • startDate: '-3d' restricts the selectable dates to three days prior to the current date.

The changeDate event captures the selected date, formats it, and logs it to the console.

Handling the changeDate Event

The changeDate event is triggered when a user selects a date. This event provides a date object containing various properties of the selected date, such as day, month, and year. You can use these properties to perform additional actions.

$('#datepicker').datepicker({
  autoclose: true,
  format: 'dd-mm-yyyy',
  startDate: '-3d'
}).on("changeDate", function(e) {
  var day = e.date.getDate();
  var month = e.date.getMonth() + 1; // Months are zero-based in JavaScript
  var year = e.date.getFullYear();

  // Add leading zero to day and month if needed
  day = day < 10 ? '0' + day : day;
  month = month < 10 ? '0' + month : month;

  var formattedDate = `${year}-${month}-${day}`;
  console.log("Formatted date: " + formattedDate);

  // Additional actions can be performed here
  // Example: Updating a hidden input field with the formatted date
  $('#hiddenDateInput').val(formattedDate);
});

In this refined example:

  • The changeDate event handler formats the selected date with leading zeros for single-digit days and months.
  • It logs the formatted date and updates a hidden input field, which could be used for form submissions.

Integrating with a Form

To demonstrate a practical use case, consider integrating the datepicker with a form. This can be useful for applications where users need to input dates, such as booking systems or event planners.

<form id="bookingForm">
  <div class="form-group">
    <label for="bookingDate">Select Booking Date:</label>
    <div id="datepicker" class="input-group date" data-provide="datepicker">
      <input type="text" class="form-control" id="bookingDate">
      <div class="input-group-addon">
        <span class="glyphicon glyphicon-th"></span>
      </div>
    </div>
  </div>
  <input type="hidden" id="hiddenDateInput" name="hiddenDateInput">
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

This example form includes a visible date picker input and a hidden input to store the formatted date for submission.

Enhancing User Experience

To further enhance user experience, consider adding features like date range selection or limiting selectable dates to weekdays. Bootstrap Datepicker offers a variety of options to cater to these requirements.

$('#datepicker').datepicker({
  autoclose: true,
  format: 'dd-mm-yyyy',
  startDate: '0d',
  daysOfWeekDisabled: [0, 6] // Disable weekends
}).on("changeDate", function(e) {
  var day = e.date.getDate();
  var month = e.date.getMonth() + 1;
  var year = e.date.getFullYear();

  day = day < 10 ? '0' + day : day;
  month = month < 10 ? '0' + month : month;

  var formattedDate = `${year}-${month}-${day}`;
  $('#hiddenDateInput').val(formattedDate);
});

In this enhanced example:

  • startDate: '0d' allows date selection starting from today.
  • daysOfWeekDisabled: [0, 6] disables selection of weekends.

Conclusion

Implementing a Bootstrap Datepicker with the changeDate event is a straightforward process that greatly improves the user experience on your website. By following this comprehensive guide, you can seamlessly integrate and customize the datepicker to suit your specific needs.

To learn more about Bootstrap Datepicker and its extensive options, click here.

https://bootstrap-datepicker.readthedocs.io/en/latest/events.html#changedate