One of the most common questions I get asked is how to set up start date and end date fields in a Divi form using the date picker in the Divi Date/Time Picker plugin and forcing the end date to always be after whatever value the user selected for the start date.
While this functionality is not part of the core plugin code, you can easily achieve this using some javascript.
Place the following javascript in one these places:
- a code module after your form
- in your child theme JS file
- in one of the fields in the Integration tab under the Divi Theme Options
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(){
var startDateFieldID = 'FIELD_ID_OF_START_DATE',
endDateFieldID = 'FIELD_ID_OF_END_DATE';
var $startDateField = document.querySelector('[data-original_id="' + startDateFieldID + '"]'),
$endDateField = document.querySelector('[data-original_id="' + endDateFieldID + '"]');
$startDateField.addEventListener('change', setMinimumEndDate);
function setMinimumEndDate(e){
let currentFp = e.target._flatpickr;
let targetFp = $endDateField._flatpickr;
let dateInValue = currentFp.selectedDates; // get current date from first date picker
let currentDateObj = new Date(dateInValue);
currentDateObj.setDate(currentDateObj.getDate() + 1); //set next datepicker init date
targetFp.config.minDate = currentDateObj;
targetFp.setDate(currentDateObj);
targetFp.open(); // comment out this line if you don't want the end date field to open automatically.
}
});
</script>
Integrating the Script into Your Form
You only need to make 2 changes to the above code to integrate it into your form. At the top of the script where it says FIELD_ID_OF_START_DATE and FIELD_ID_OF_END_DATE – change these to the field IDs you’re using for these fields on your form.
Consider the following example.
If we used start_date and end_date as our field IDs like in the images above, then the top part of our code would look like this:
...
var startDateFieldID = 'start_date',
endDateFieldID = 'end_date';
...
It’s also important to note that for the best results, I recommend using only lower case letters, numbers and underscores in your Field ID.
I consider this best practice on every Divi Contact Form whether you’re using a plugin like the Divi Date/Time Picker, Divi Multistep Contact Form or any custom code. Standardizing your field IDs will also make your life easier if you need to debug something down the road.
If you use spaces and special characters like apostrophes or commas you could experience unexpected results.
Optional Settings
Towards the end of the script you’ll notice a line that says:
targetFp.open();
This causes the End Date field to open automatically when the user selects the start date. If you wish to disable this field from opening automatically, simply comment this line out by placing 2 forward slashes before it. For example:
// targetFp.open();