同一id上Jquery日期选择器的两种不同日期格式

Two different date format of Jquery date picker on same id

本文关键字:日期 两种 格式 选择器 id Jquery 同一      更新时间:2023-12-06

我正试图在同一id上获取Jquery日期选择器,该选择器在事件发生后更改其日期格式。我尝试了下面的代码片段,但无法按预期执行。

JS代码

function dateselect(){
    var type = jQuery('#uploadtype').val()
    if(type == "monthly"){ //if user select month as dropdown
        jQuery('#datepicker').datepicker( {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function(dateText, inst) { 
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
            }
        });
    }
    else{
            jQuery('#datepicker').datepicker({
                  beforeShowDay: displayValidDates,
                  maxDate: '-1w',
                  constrainInput: true,
                dateFormat:"yy-mm-dd"
            });
         }
}

如果您想在运行时根据条件更改格式,最好使用默认值初始化日期选择器,并且您的函数只更改所需的格式和其他选项。

试试。。。。

jQuery('#datepicker').datepicker({
              beforeShowDay: displayValidDates,
              maxDate: '-1w',
              constrainInput: true,
            dateFormat:"yy-mm-dd"
         });
function dateselect(){
var type = jQuery('#uploadtype').val()
if(type == "monthly"){ //if user select month as dropdown
    $("#datepicker").datepicker( "option", "dateFormat", "MM yy" );
}
else{
    $("#datepicker").datepicker( "option", "dateFormat", "yy-mm-dd" )
}
}

您可以查看此示例以了解更多信息:

https://jqueryui.com/resources/demos/datepicker/date-formats.html