Support Center

Flatpickr DateTime Picker for Jumpseller Products

Use Javascript Responsibly: Implementing JavaScript code on your website, especially in e-commerce sites, without having a technical background can be dangerous. It may lead to unintended consequences, security vulnerabilities, and negatively impact the user experience. It is highly recommended that you seek assistance from professional web developers or experts in web design to ensure that the code is properly implemented, secure, and optimized for your site. Properly executed code will help maintain a high-quality user experience and protect sensitive information that is critical to the success of your e-commerce business


Flatpickr is a lightweight, powerful, and highly customizable JavaScript library for creating date and time pickers on your web pages. This guide will walk you through the process of adding a Flatpickr date time picker to your Jumpseller product page and provide explanations for the code. Implementing this functionality will allow your customers to schedule orders and adhere to business restrictions such as holidays and business hours.

Requirements

To use Flatpickr, you will need to include the following resources in your Jumpseller product page HTML file:

  • Flatpickr CSS file: This file provides the necessary styling for the date time picker.
  • Flatpickr JavaScript file: This file includes the Flatpickr library, which provides the functionality for the date time picker.

To include these files, add the following lines to the head section of your Layout Template:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

Usage

First and foremost, you need to create Option type Text Field with the name ‘Date.’ You are free to choose a different name, but keep in mind that you will need to update the code accordingly. This field will remain hidden. In order to implement a date-time picker within your Jumpseller product template, add this code to create a datepicker field. This will be compatible with any Bootstrap-based theme:

<div class="col-12 col-md-6">
<label for="datetimepicker" class="form-control-label">Select Date</label>
<input type="text" id="datetimepicker" name="datetimepicker">
</div>

This implementation enables the selection of date and time values using a Flatpickr date-time picker, with configurations specified in the script. The selected value will be inserted into the custom input field named ‘Date.’ Customers can now conveniently use this input field to choose a date and time when placing orders. This feature assists your store in collecting essential information and adhering to business constraints, such as holidays and operational hours.

The code

The date time picker is implemented using the Flatpickr library, which is a lightweight and customizable datetime picker.

<script>
// Hides the input that contains the Date Label
document.addEventListener("DOMContentLoaded", function() {
    const labels = document.getElementsByTagName("label");
    for (const label of labels) {
        if (label.textContent.trim() === "Date") {
            const containingDiv = label.parentElement;
            if (containingDiv) {
                containingDiv.style.display = "none";
            }
        }
    }
});

// Get today's date and time
var today = new Date();
var currentHour = today.getHours();
var currentMinute = today.getMinutes();

// Calculate the minimum date based on current time
var minDate;
if (currentHour >= 17) {
    minDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 2);
} else {
    minDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
}

// Set up the holiday dates to be blocked
var holidays = [
    "2022-09-16",
    "2022-11-19",
    "2022-12-24"
];

// Initialize the Flatpickr date time picker with Spanish locale and Monday as the first day of the week
flatpickr("#datetimepicker", {
    enableTime: true, // Enable time selection
    dateFormat: "Y-m-d H:i:S", // Set the custom date and time format
    time_24hr: true, // Use 24-hour time format
    minDate: minDate, // Set the minimum selectable date
    disable: [
        function(date) {
            // Disable Sundays
            return date.getDay() === 0;
        }
    ].concat(holidays), // Disable Sundays and the specified holiday dates
    minTime: "09:00", // Set the starting business hours
    maxTime: "18:00", // Set the closing business hours
    hourIncrement: 1, // Set the hour increment to 1
    weekNumbers: true, // Display week numbers
    locale: { // Set the locale to Spanish and translate weekdays and months
        firstDayOfWeek: 1,
        weekdays: {
            shorthand: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"],
            longhand: [
                "Domingo",
                "Lunes",
                "Martes",
                "Miércoles",
                "Jueves",
                "Viernes",
                "Sábado"
            ]
        },
        months: {
            shorthand: [
                "Ene",
                "Feb",
                "Mar",
                "Abr",
                "May",
                "Jun",
                "Jul",
                "Ago",
                "Sep",
                "Oct",
                "Nov",
                "Dic"
            ],
            longhand: [
                "Enero",
                "Febrero",
                "Marzo",
                "Abril",
                "Mayo",
                "Junio",
                "Julio",
                "Agosto",
                "Septiembre",
                "Octubre",
                "Noviembre",
                "Diciembre"
            ]
        }
    },
    onChange: function(selectedDates, dateStr, instance) {
        // Update the hidden input with the selected date when it changes
        $("label:contains('Date') + div input").val(dateStr);
    }
});

</script>

Code Explanation

The script provided initializes a Flatpickr date time picker with various customizations. Here’s a breakdown of the code:

  1. Hiding the “Date” input:
       document.addEventListener("DOMContentLoaded", function() {
           const labels = document.getElementsByTagName("label");
           for (const label of labels) {
               if (label.textContent.trim() === "Date") {
                   const containingDiv = label.parentElement;
                   if (containingDiv) {
                       containingDiv.style.display = "none";
                   }
               }
           }
       });
    

    This part of the code waits for the DOMContentLoaded event, which is fired when the document’s initial HTML has been completely loaded and parsed. It then gets all the label elements and iterates through them. If a label has the text content “Date”, the script hides its parent div by setting the CSS display property to “none”.

  2. Getting today’s date and time and calculating the minimum date:
       var today = new Date();
       var currentHour = today.getHours();
       var currentMinute = today.getMinutes();
    
       var minDate;
       if (currentHour >= 17) {
           minDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 2);
       } else {
           minDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
       }
    

    This part of the code gets the current date and time and calculates the minimum date based on the current hour. If the current hour is 17 (5 PM) or later, the minimum date is set to two days from today. Otherwise, the minimum date is set to one day from today.

  3. Setting up the holiday dates to be blocked:
       var holidays = [
       "2022-09-16",
       "2022-11-19",
       "2022-12-24"
       ];
    

    This part of the code initializes an array of holiday dates in string format. These holiday dates will be blocked in the Flatpickr datetime picker.

  4. Initializing the Flatpickr datetime picker:
       flatpickr("#datetimepicker", {
         ...
       });
    

    This part of the code initializes a Flatpickr datetime picker by targeting an element with the ID datetimepicker. It also contains several options to customize the picker:

    • enableTime: true - Enables time selection in the datetime picker.
    • dateFormat: "Y-m-d H:i:S" - Sets the custom date and time format.
    • time_24hr: true - Uses a 24-hour time format.
    • minDate: minDate - Sets the minimum selectable date.
    • disable: [...] - Disables Sundays and the specified holiday dates.
    • minTime: "09:00" - Sets the starting business hours.
    • maxTime: "18:00" - Sets the closing business hours.
    • hourIncrement: 1 - Sets the hour increment to 1.
    • weekNumbers: true - Displays week numbers.
    • locale: {...} - Sets the locale to Spanish and translates weekdays and months.
    • onChange: function(selectedDates, dateStr, instance) {...} - Updates the hidden input with the selected date when it changes.

Step by Step Video Implementation Example

In conclusion, the code provided in this article offers a customized and user-friendly Flatpickr datetime picker for your website, ensuring that users can easily select an available date and time within the given constraints. By understanding and implementing this code with the help of professionals, you can enhance the overall user experience and functionality of your website.

Start your journey with us!

Free trial for 14 days. No credit card required.