Skip to content

Commit 684f516

Browse files
committed
gw-preserve-datepicker-date-selection-when-changing-months.js: Fixed an issue with edge cases like 29 February, 31 April etc.
1 parent b7802b1 commit 684f516

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

gravity-forms/gw-preserve-datepicker-date-selection-when-changing-months.js

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,28 @@ gform.addFilter( 'gform_datepicker_options_pre_init', function( optionsObj, form
1818
var selectedDate = $(this).datepicker('getDate');
1919
var day = selectedDate ? selectedDate.getDate() : 1;
2020

21-
// Set the new date with the updated month and year
21+
// Helper function to check if the given year is a leap year
22+
const isLeapYear = year => new Date(year, 1, 29).getMonth() === 1;
23+
24+
// Determine the maximum days for the selected month
25+
let maxDay;
26+
if (month === 2) {
27+
// February
28+
maxDay = isLeapYear(year) ? 29 : 28;
29+
} else if ([4, 6, 9, 11].includes(month)) {
30+
// April, June, September, November
31+
maxDay = 30;
32+
} else {
33+
// All other months
34+
maxDay = 31;
35+
}
36+
37+
// Adjust the day if it exceeds the maximum days in the selected month
38+
day = Math.min(day, maxDay);
39+
40+
// Set the new date with the updated month, year, and adjusted day
2241
$(this).datepicker('setDate', new Date(year, month - 1, day));
2342
}
24-
25-
return optionsObj;
43+
44+
return optionsObj;
2645
} );

0 commit comments

Comments
 (0)