0

我们有一个文本框,我们既要触发 jQuery UI 日期选择器,又要能够在文本框中徒手输入文本。我们目前正在使用同一文本框上的 jQuery UI Mask 和 DatePicker 来实现这一点。但是,我必须“破解”面具才能让它工作 - 因为,一旦你自由输入:04/29/19

然后,在您完成输入“83”以完成四位数日期之前,datepicker 会触发一些事件,将 datepicker 的当前日期移动到您正在输入的日期,但是,它也会删除到目前为止的整个日期。所以目标是输入日期:04/29/1983,但日期选择器删除了我到目前为止的内容。起初我们认为掩码有问题,但现在我只需要弄清楚如何避免错误触发 datepicker 事件。任何帮助将不胜感激!

对不起,代码示例:

$('#txbxSocialHistoryDate').datepicker({
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true
 });

$('#txbxSocialHistoryDate').mask("99/99/9999", { placeholder: " " });  
4

2 回答 2

1

我有同样的问题,但这不是 JQuery datepicker 的问题,问题是 MASK 插件,当你写 2 或 4 位数字时,jquery 会触发事件,但是当事件被触发时,也会调用 MASK 事件,并发生冲突. 解决方案将是一个包含掩码的 JQuery 日期选择器。

我使用触发按钮解决了我的问题,因为如果用户想要写日期,他只需输入日期就可以了,但是,如果他们想要选择,只需单击按钮触发器。

尝试一下。 http://jqueryui.com/demos/datepicker/#icon-trigger

于 2011-06-08T22:58:38.043 回答
1

上面的答案绝对适用于这个问题。但是,没有触发按钮,我想出了一个解决方案,如下:

$('#txbxSocialHistoryDate').datepicker({
            showButtonPanel: true,
            changeMonth: true,
            changeYear: true,
            dateFormat: 'mm/dd/yyyy',
            onSelect: function (dateText, inst) {
                UIUtilities_jQueryDatePickerOnCloseEventIfAlsoMasked(this, 'txbxSocialHistoryDate', dateText);
            },
            onClose: function (dateText, inst) {
                UIUtilities_jQueryDatePickerOnCloseEventIfAlsoMasked(this, 'txbxSocialHistoryDate', dateText);
            }
});

$('#txbxSocialHistoryDate').mask("99/99/9999", { placeholder: " " });

function UIUtilities_jQueryDatePickerOnCloseEventIfAlsoMasked(thisDatePicker, txbxOfDatePicker, dateText) {
    // when the calendar closes, determine if this was entered by hand, or by the calendar
    var textInBox = $('#' + txbxOfDatePicker).val();

    // if by the calendar, it will have 2 years attached, so we then shave the 2nd year off the end
    // there is a brief flash of the incorrect year, but short of taking off both the masking & calendar on this one textbox, this will work...
    if (textInBox.length > 10) {
        $('#' + txbxOfDatePicker).val(dateText.substring(0, dateText.length - 4));
    }

    // this fixes the tabbing issue mentioned; now when you tab out of the calendar, it will move on to the appropriate control...
    thisDatePicker.focus();
}

所以我做了什么:

  • 声明日期选择器,但格式为:'mm/dd/yyyy',我错误地认为是它出现的样子。但是,在jQuery DateFormat 定义站点上,这实际上使日期在选择时被格式化为:mm/dd/yyyyyyyy(年份重复两次)。'yy' == DateFormat 中的 4 位数年份,显然。这个最初的错误让我找到了答案。
  • 屏蔽您已经将日期选择器绑定到的相关日期字段。
  • 使用更长的日期条目,删除我的面具的触发事件将停止。我所要做的就是放入我在 datepicker 的 onSelect 和 onClose 函数上创建的自定义方法中,现在一切正常。它基本上从日期选择器的选择中去除了不必要且不正确的双年。掩码和具有 4 位数年份格式的日期选择器现在可以一起使用。
于 2011-06-09T14:45:55.293 回答