Search code examples
jqueryjquery-uidatepickerjquery-ui-datepicker

Change DatePicker changing the option selected in a dropdown


I want to change the datepicker's format depending on which option I select in a dropdown (Daily or Monthly selection). Here is my code:

$("#date-format").change(function () {
    if ($(this).find("option:selected").text() == "Daily") {
        $('.date-picker').datepicker({
            dateFormat: "dd/mm/yy"
        });
    }
    else if ((this).find("option:selected").text() == "Monthly") {
        $('.date-picker').datepicker({
            dateFormat: "mm/yy",
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            onClose: function (dateText, inst) {

                function isDonePressed() {
                    return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
                }

                if (isDonePressed()) {
                    var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                    $(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');

                    $('.date-picker').focusout()//Added to remove focus from datepicker input box on selecting date
                }
            },
            beforeShow: function (input, inst) {

                inst.dpDiv.addClass('month_year_datepicker')

                if ((datestr = $(this).val()).length > 0) {
                    year = datestr.substring(datestr.length - 4, datestr.length);
                    month = datestr.substring(0, 2);
                    $(this).datepicker('option', 'defaultDate', new Date(year, month - 1, 1));
                    $(this).datepicker('setDate', new Date(year, month - 1, 1));
                    $(".ui-datepicker-calendar").hide();
                }
            }
        })
    }
})

Do you know how to change the format after the first implementation of the date picker?


Solution

  • You can use the option method, in your case something like:

    $('.date-picker').datepicker( "option", "dateFormat", "mm/yy");