views:

110

answers:

2

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";
}
+6  A: 

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.)

Peter Boughton
+1 correct answer, though I think "passing a reference to the function itself" would be slightly clearer "passing the value of the function"
Kieron
Agreed, that wording wasn't great; I've updated it and incorporated your suggestion. :)
Peter Boughton
passing a reference to the function does't work. It just returns empty string when I select a date. hmmm????
Schotime
dateFormat needs a string, so he's doing it right.
Matthew Crumley
Well that's not what you asked - you asked why it was being called whether elements are found or not. Looking at the actual API docs, it seems dateFormat is a string argument not a function, so I'll have to update my answer...
Peter Boughton
Yeah i thought so. Thanks for the response though Peter. Helped me understand it better. Cheers.
Schotime
+5  A: 

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()>
    });
});
Chetan Sastry
That makes sense!
Schotime