I’m really curious as to why this code to set the defaultDate to a date 25 years ago from today works properly…
$('div.recipient_modal input[name="birth_date"]:first').datepicker({
changeMonth: true,
changeYear: true,
defaultDate: get_recipient_default_birth_date(),
yearRange: 'c-125:' + new Date().getFullYear()
});
function get_recipient_default_birth_date()
{
var d = new Date();
var y = d.getFullYear() - 25;
d.setFullYear(y);
return $.datepicker.formatDate('mm/dd/yy', d);
}
But when I try to set the default date to 25 years ago from today using an anonymous function rather than calling a named function that has the same code like below…
$('div.recipient_modal input[name="birth_date"]:first').datepicker({
changeMonth: true,
changeYear: true,
defaultDate: function() {
var d = new Date();
var y = d.getFullYear() - 25;
d.setFullYear(y);
return $.datepicker.formatDate('mm/dd/yy', d);
},
yearRange: 'c-125:' + new Date().getFullYear(),
});
I get the following error in the console…
Uncaught TypeError: Object function () {
var d = new Date();
var y = d.getFullYear() - 25;
d.setFullYear(y);
return $.datepicker.formatDate('mm/dd/yy', d);
} has no method 'getTime'
Can anyone explain the difference in these two assignments and why the anonymous function doesn’t work but the named function does?
Thank You.
You already described why it isn’t working: You’re setting the anonymous function as the value.
Not the return value from the anonymous function.
In your first, working, example, you are calling the function which returns the value for the default. In your second example, you are simply defining an anonymous function and assigning it directly as the value – without calling it.
If you want to use an anonymous function like that, you will need to actually call it, like so: