【问题标题】:Userscript to autofill jQuery UI Datepicker - wrong date format用户脚本自动填充 jQuery UI Datepicker - 错误的日期格式
【发布时间】:2016-04-18 13:27:34
【问题描述】:

我正在尝试自动填充jQuery UI datepicker,但日期以MM/DD/YYYY 格式粘贴。我需要将其粘贴为yy-mm-dd 格式。使用本机日期选择器功能时,日期会正确填写。我正在尝试使用以下方法设置日期,但每种方法都填写了错误的格式。如何正确设置yy-mm-dd 格式的日期,而不是默认的MM/DD/YYYY 格式?

页面使用 jQuery 2.1.4 和 jQuery UI 1.11.4。

// initialize date
var cur = new Date();

// methods I've tried
$('.selector').datepicker('setDate', cur);

$('.selector').datepicker('formatDate', 'yy-mm-dd');
$('.selector').datepicker('setDate', cur);

$('.selector').datepicker('option', 'formatDate', 'yy-mm-dd');
$('.selector').datepicker('setDate', cur);

$('.selector').datepicker('option', 'formatDate', 'yy-mm-dd');
$('.selector').datepicker('refresh');
$('.selector').datepicker('setDate', cur);

// from answers below
$('.selector').datepicker({dateFormat: 'yy-mm-dd'});
$('.selector').datepicker('setDate', cur);

// this method changes the format displayed in the field, but the form's
// validation throws an error that it is in the wrong format. focus/unfocus
// on the field manually after this sets the date back to the previous format.
$('.selector').datepicker('setDate', cur);
var s = cur.getFullYear() + '-' + (('0' + (cur.getMonth() + 1)).slice(-2)) +
        '-' + (('0' + (cur.getDate())).slice(-2));

【问题讨论】:

    标签: jquery date jquery-ui datepicker


    【解决方案1】:

    试试这个:

    $(".selector").datepicker({dateFormat: "yy-mm-dd"});
    

    【讨论】:

    • 不幸的是没有工作。将其添加到我的帖子中以表明它没有。
    • 您是否将 jquery.ui 文件与 jquery 文件一起添加?
    【解决方案2】:
    $('.selector').datepicker({dateFormat: 'yy-mm-dd'});
    var curFormatted = $.datepicker.formatDate('yy-mm-dd', cur);
    $('.selector').datepicker('setDate', curFormatted);
    

    【讨论】:

    • 在第二行,我得到Uncaught TypeError: Cannot read property 'formatDate' of undefined(…)。我不确定这是原生版本的 jQuery UI 的问题,还是我做错了什么。
    • 你用的是什么版本的jquery和jquery-ui?
    • jQuery 2.1.4 和 jQuery UI 1.11.4。也添加到问题中以供参考。
    • 设置日期格式后使用$('.selector').datepicker('setDate', s); 而不是$('.selector').datepicker('setDate', cur);
    【解决方案3】:

    我觉得很傻,但该站点实际上使用了bootstrap-datepicker,而不是 jQuery UI 日期选择器。我真诚地道歉。

    【讨论】:

      猜你喜欢
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 2014-04-19
      相关资源
      最近更新 更多