Search code examples
jquery-uidatepickerjquery-ui-datepicker

Setting dateFormat on jQuery UI datepicker, on a non-empty field


I need my dateformat to be in dd/mm/yyyy and therefore need to use this following code:

$(".date-pick").datepicker( "option", "dateFormat", "dd/mm/yy");

But, when using just this line, I don't get the datepicker popup calendar.

If I use this, i get the popup, but then I lose the pre-set date in the value of the field

$(".date-pick").datepicker();
$(".date-pick").datepicker( "option", "dateFormat", "dd/mm/yy");

See here - https://jsfiddle.net/kneidels/hkbgzvmt/

What code can I use to (1) have the dd/mm/yyyy format, as well as (2) have the pre-set date value shown?

Thanks.


Solution

  • The intended way is to define the defaultDate and dateFormat when instantiating the datepicker: https://jsfiddle.net/tg7yv149/1/

    $(function() {
      $(".date-pick").datepicker({
        defaultDate: $(this).val(),
        dateFormat: "dd/mm/yy"
      });
    });
    

    Another way that works is to store the value in a variable, instantiate the datepicker, then apply the value again: https://jsfiddle.net/Lyneb7j9/

    $(function() {
        var myval = $(".date-pick").val();
      
        $(".date-pick").datepicker();
        $(".date-pick").datepicker( "option", "dateFormat", "dd/mm/yy");
        $(".date-pick").val(myval);
    });