Bootstrap Datepicker re-initialize date format

后端 未结 3 569
执念已碎
执念已碎 2021-01-14 18:51

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/yy

相关标签:
3条回答
  • 2021-01-14 19:02

    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

    0 讨论(0)
  • 2021-01-14 19:19

    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);
    });
    
    0 讨论(0)
  • 2021-01-14 19:21

    When you have many date pickers, the you can use a class selector and reset all of them, and initialize using the class. Code sample below. In the example, all the input elements will have the class date-picker

    function resetDatePickers(){
        $('.date-picker').each(function(index){
           $(this).datepicker('remove');
        });
    
        $('.date-picker').datepicker({
            format: "dd/mm/yyyy",
            startView: 2,
            orientation: "top auto"
        });
    }
    
    
    resetDatePickers();
    
    0 讨论(0)
提交回复
热议问题