How to Enable Range Selection in Bootstrap 5 Datepicker

Nov 27, 2023 . Admin

Hi dev

Have you ever found yourself needing a user-friendly date range selection feature for your website? I recently faced this challenge and successfully implemented it using Bootstrap 5 Datepicker. In this step-by-step guide, I'll share the process, making it accessible for both coding beginners and experts alike. By the end, you'll be able to enhance your web application's functionality and provide users with a seamless way to choose date ranges.

Step 1: Prerequisites

Ensure that you have a working Bootstrap 5 project with Bootstrap CSS and JavaScript files included. Additionally, integrate the Bootstrap Datepicker plugin, following the guidelines from your previous article.

Step 2: Create the Input Fields

Create two input fields in your HTML for selecting the start and end dates of the range. Here's an example:

<input type="text" id="startDate" data-datepicker>
<input type="text" id="endDate" data-datepicker>	
Step 3: Initialize the Datepicker for Range Selection

Initialize the Datepicker for both input fields in your JavaScript by setting the range option to true:

$(document).ready(function () {
    $('#startDate').datepicker({
        format: "mm/dd/yyyy",
        todayHighlight: true
    });

    $('#endDate').datepicker({
        format: "mm/dd/yyyy",
        todayHighlight: true
    });
});	

The format option specifies the date format, and todayHighlight highlights the current date.

Step 4: Enable Range Selection

Enable the range selection feature by setting the inputs option, allowing you to pair the start and end date fields:

$(document).ready(function () {
    $('#startDate').datepicker({
        format: "mm/dd/yyyy",
        todayHighlight: true
    });

    $('#endDate').datepicker({
        format: "mm/dd/yyyy",
        todayHighlight: true
    });

    $('#startDate').on('changeDate', function (selected) {
        var startDate = new Date(selected.date.valueOf());
        $('#endDate').datepicker('setStartDate', startDate);
    });

    $('#endDate').on('changeDate', function (selected) {
        var endDate = new Date(selected.date.valueOf());
        $('#startDate').datepicker('setEndDate', endDate);
    });
});	

When the start date changes, it sets the minimum allowed date for the end date, creating a range selection effect.

Conclusion

Enabling date range selection in Bootstrap 5 Datepicker is a simple yet impactful enhancement for your web application. Empower your users with the flexibility to make choices relevant to their needs.

#Laravel