手动输入的jQuery Datepicker格式日期 [英] jQuery Datepicker Format Date on Manual Input

查看:135
本文介绍了手动输入的jQuery Datepicker格式日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式为dd-MM-yyyy的jQuery datepicker.

I have a jQuery datepicker with format: dd-MM-yyyy.

默认情况下,日期选择器会将诸如 1-2-3 1-2-99 之类的日期转换为 01-02-2003 01-02-1999 .但是,只有在您按Enter键或从日期选择器中选择日期时,才会出现这种情况.我尝试使用以下方式在离开字段时自动设置字段格式:

By default the datepicker converts dates such as 1-2-3 and 1-2-99 to 01-02-2003 and 01-02-1999 respectively. However, this is only the case when you press enter or choose the date from the datepicker. I tried to auto format the field when leaving the field by using:

$j('.datepicker').live('blur', function(){
    $j(this).datepicker('setDate', $j(this).datepicker('getDate'));
});

在这种情况下,我使用的是Datepicker本身的实用程序功能setDate和getDate.例如,当您使用键盘并使用TAB键输入日期时,此方法将起作用.但是,当您尝试用鼠标选择日期时,模糊触发器也会激活.因此,您必须用鼠标选择两次日期,因为第一个模糊事件会将旧值设置回原来的值.

In this case I am using the utility function setDate and getDate of the Datepicker itself. This works when you enter the date by using your keyboard and using the TAB-key for example. However, the blur trigger also activates when you try to pick the date with your mouse. Therefore you have to choose the date twice with your mouse, because the first one the blur event sets the old value back.

我有什么想念的活动可以使用吗?

Is there any event I am missing I can use?

解决方法

不太优雅,但这是部分解决方案:

Not very elegant but it is a partial solution:

var timeout;
$j('#geboortedatum').live('keypress', function() {
    if(timeout) {
        clearTimeout(timeout);
        timeout = null;
    }
    timeout = setTimeout(formatDate, 1000);
});

function formatDate() {
    var gebdat = $j('#geboortedatum').val();
    var dashCount = gebdat.split('-').length - 1;
    if(dashCount == 2 && gebdat.length >= 5) {
        $j('#geboortedatum').datepicker('setDate', $j('#geboortedatum').datepicker('getDate'));
    }
}

推荐答案

我只是在datepicker istelf中使用onClose事件:

I just use the onClose event within datepicker istelf:

$(function(){
    var $myDate = $('#myDate');
    $myDate.datepicker({
      dateFormat: 'dd-mm-yy',
      onClose: function(dateText, inst) {
          $(this).datepicker('option', 'dateFormat', 'dd-mm-yy');                
    }
});

});

http://jsfiddle.net/RpUSL/

这篇关于手动输入的jQuery Datepicker格式日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆