Last active
January 23, 2025 07:29
-
-
Save saifsultanc/d88f8b1a9eef733c72f2d76b7137a419 to your computer and use it in GitHub Desktop.
gw-use-html5-datepicker-with-gpld.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(document).ready(function($) { | |
var onlyConvertOnMobile = false; // Change to false if you wish for all devices to use HTML5 datepicker | |
var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); | |
if ( isMobile || onlyConvertOnMobile === false ) { | |
let $datepicker = $('#input_GFFORMID_1'); // Replace 1 with your field ID | |
// Ensure Gravity Forms' Datepicker is Destroyed | |
if ($datepicker.hasClass('hasDatepicker')) { | |
$datepicker.removeClass('hasDatepicker initialized'); | |
$datepicker.datepicker('destroy'); | |
} | |
// Change Input Type to Native Datepicker | |
$datepicker.attr('type', 'date'); | |
// Preserve Min/Max Dates | |
let minDate = $datepicker.datepicker('option', 'minDate'); | |
let maxDate = $datepicker.datepicker('option', 'maxDate'); | |
if (minDate) { | |
let formattedMinDate = $.datepicker.formatDate('yy-mm-dd', minDate); | |
$datepicker.attr('min', formattedMinDate); | |
} | |
if (maxDate) { | |
let formattedMaxDate = $.datepicker.formatDate('yy-mm-dd', maxDate); | |
$datepicker.attr('max', formattedMaxDate); | |
} | |
// 🔴 Disable Specific Dates in HTML5 Datepicker (JS Workaround) | |
let disabledDates = $datepicker.datepicker('option', 'beforeShowDay'); | |
if (disabledDates) { | |
$datepicker.on('input', function() { | |
let selectedVal = $(this).val(); | |
let isDisabled = disabledDates(new Date(selectedVal))[0] === false; | |
if (isDisabled) { | |
alert('This date is not available. Please select another.'); | |
$(this).val(''); // Clear invalid date | |
} | |
}); | |
} | |
// Preserve Selected Date (if any) | |
let selectedDate = $datepicker.val(); | |
if (selectedDate) { | |
let formattedDate = selectedDate.replace(/[^0-9\-]/g, ''); // Clean format | |
$datepicker.val(formattedDate); | |
} | |
$datepicker.on('click', function() { | |
$('#ui-datepicker-div').remove(); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment