【问题标题】:jQueryUI DatePicker Customizing the YearjQueryUI DatePicker 自定义年份
【发布时间】:2010-10-28 17:45:18
【问题描述】:

我有一个使用 jqueryui DatePicker 的 Datepicker。

行为要求是:

  • 用户可以为朋友存储生日。如果已知,用户应该能够存储年份,或选择“N/A”。

  • 如果选择“N/A”,则将 1900 年存储在数据库中,并仅在用户的输入字段中显示日期和月份。

  • 下拉列表应从 1950 年开始,但显示从当前日期起过去 100 年(

这是我到目前为止所得到的,但它很笨拙......这是轻描淡写的。并且由于某种原因,如果用户选择了一个日期,但没有更改年份下拉菜单,则存储的是当前年份,而不是 1900。

(在 json 调用的上下文中)。肯定有更好的办法。

var birthday_options = {changeMonth: true, changeYear: true, yearRange: '1900:2010',
        onClose: function(dateText, inst) {
        contact.field_updater('birthday').call(this);
        $('input.mng-birthday').val(function(i, val) {
                       return val.replace('/1900', '');
                    });
        },
        beforeShow: function (input) {
                      setTimeout(function () {
                        $('select.ui-datepicker-year option:first').text('N/A');                                                                 
                      }, 1);
                    }},

.find('.mng-birthday').val(data.birthday || 'Unknown')
  .datepicker(birthday_options)
.end(); 

【问题讨论】:

    标签: javascript jquery ajax datepicker jquery-ui


    【解决方案1】:

    Click here to see a demo.

    当您发现自己超出范围时,可以轻松修改 jQuery UI 源代码。您只需要更改 _generateMonthYearHeader 的函数定义:

    // StackOverflow question: Add option for N/A
    html += '<option value="1900">N/A</option>';
    

    并对 _selectDay 进行此更改以省略选择 N/A 的年份。

    // StackOverflow question: format the date
    if (inst.currentYear == 1900)
        this._selectDate(id, (inst.currentMonth + 1) + "/" + inst.currentDay);
    else
        this._selectDate(id, this._formatDate(inst, inst.currentDay,
                         inst.currentMonth, inst.currentYear));
    

    在脚本面板中,您有核心 UI 脚本、修改后的 datpicker 脚本和设置:

    $(document).ready(function() {
        var year = new Date().getFullYear();
    
        $(".mng-birthday").datepicker({
            changeYear: true,
            // The year range is from the current year to 100 years before
            yearRange: (year - 100) + ":" + year,
            // The default date is january 1st fifty years before the current year
            defaultDate: "01/01/1900"
        });
    });
    

    【讨论】:

    • 我知道这应该如何工作,并且显然在演示中也可以,但是当我选择 N/A 时,我继续得到 2016 年。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2020-11-08
    相关资源
    最近更新 更多