Why does the function run when there are no elements found?
-
10-07-2019 - |
Question
I have the following code, however if the input.formdate
is not found it will still run the getDateFormat
function. This doesn't make sense to me.
Does anyone know the reason?
$(function() {
$("input.formdate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: getDateFormat()
});
});
function getDateFormat()
{
var format = 'DMY';
if (document.edit_form && document.edit_form.date_format)
format = document.edit_form.date_format.value;
if (format = "DMY")
return "dd-mm-yy";
else
return "mm-dd-yy";
}
Solution
The getDateFormat function is run as soon as Javascript is parsed because it is within an object literal notation.
Your expression is evaluated as
$(function() {
$("input.formdate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: <RESULT_FROM_CALLING_getDateFormat()>
});
});
OTHER TIPS
Old Answer:
(based on mis-understanding of question - see comments)
Because you're calling the function and passing its result, instead of what you should be doing: passing a reference to the function (i.e. treating it as a variable).
Do this:
$(function() {
$("input.formdate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: getDateFormat
});
});
Update:
After checking the jQuery UI DatePicker API, you need to pass a string to dateFormat.
If you don't want your function to execute unless there is at least one input with a class of formdate, you need to do this:
if ( $('input.formdate').length > 0 )
{
$("input.formdate").datepicker
(
{ changeMonth: true
, changeYear: true
, dateFormat: getDateFormat()
}
);
}
Alternatively, you could do it with an inline if:
$("input.formdate").datepicker
(
{ changeMonth: true
, changeYear: true
, dateFormat:
$('input.formdate').length > 0 ? getDateFormat() : 'dd-mm-yy'
}
);
Though it's debatable if that's more or less readable.
(There's probably still a shorter way than that, but I have to go now.)