I’ve had quite a few clients complain about when they change the date on the JQuery Datepicker, it doesn’t update the date… This is because they change the month/year and expect it to update the date without selecting one.
So I thought I’d help them out and update the date for them automatically using the onChangeMonthYear() function.
My code is below. When I change the month or year, it takes me to 2017 or 1987… I don’t understand what is wrong. Am I missing something?
$('#member_birthday_full').datepicker({
altField: '#member_birthday',
altFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
dateFormat: 'DD, d MM yy',
showAnim: 'slideDown',
yearRange: '-125:+0',
onChangeMonthYear:function(y, m, i){
var d = i.selectedDay + '';
if (d.length < 2)
d = '0' + d;
var m = m + '';
if (m.length < 2)
m = '0' + m;
$(this).datepicker( "setDate", y + '-' + m + '-' + d );
}
});
The easiest solution (see demo) is to set the new date using a Date object:
From the fine manual:
But you’re setting the new date in the
altFormat. Then the datepicker tries its best to parse theyy-mm-dddate using theDD, d MM yyformat and you end up in 1887 all dazed and confused and wondering where your DeLorean is.You’ll also want to decide what you’re going to do if they try to move from, say, January 31 to February. You’d probably want to go to February 28 (or 29 in a leap year). Similar issues will come up if you start at January 29, January 30, May 31, … and go forward one month; slightly different issues arise if you start at June 30 and try to go back one month. I’ll leave that as an exercise for the reader.