Search code examples
javascriptjqueryfunctionjquery-uijquery-ui-datepicker

Why does the function run when there are no elements found?


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()>
        });
    });