Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Datepicker re-initialize date format

I have Bootstrap datepicker with default format mm/dd/yyyy, and I have select where I can change format from mm/dd/yyyy to dd/mm/yyyy and reverse.

On select change I want to my datepicker change format.

I tried

find('#options-date_format').on('change', function(){
    $("#picker").datepicker({format: formatDate})
});

but It's not working, and I can't find way of doing this. Also tried to remove / destroy datepicker but I got javascript error.

like image 850
Djomla Avatar asked Dec 01 '22 02:12

Djomla


2 Answers

I think the below approach is working,

1, Whenever changing the format, de-attach and then re-attach back to the element.

$("#dp3").datepicker();  // initialization
$('select').on('change', function () {
    var d = $('select option:selected').text();
    if (d == 2) {
        $("#dp3").datepicker('remove'); //detach
        $("#dp3").datepicker({          //re attach
            format: "dd/mm/yyyy"
        })
    } else {
        $("#dp3").datepicker('remove'); //detach
        $("#dp3").datepicker({          //re attach
            format: "mm/dd/yyyy"
        })
    }
});

JSFiddle

like image 101
Praveen Avatar answered Dec 04 '22 11:12

Praveen


Ok I resolve this extending bootstra-datepicker.js

setFormat: function(format) {
    this.format = DPGlobal.parseFormat(format);
}

And call that function

find('#options-date_format').on('change', function(){
    $("#picker").datepicker('setFormat', newFormat);
});
like image 42
Djomla Avatar answered Dec 04 '22 10:12

Djomla