2013-07-11 23 views
0

我正在使用自定义时间选择器。我想要做的是:如果用户输入1234它将更改为12:34。问题根本不存在(我没有例外)。以下是我迄今为止:使用正则表达式分隔4位数:

// check time entry 
(function ($) { 
    String.prototype.Timeset = function(){ 
     return this.replace(/^\d{2}\:\d$/,"$1,"); 
    } 
    $.fn.Time = function(){ 
     return this.each(function(){ 
      $(this).val($(this).val().Timeset()); 
     }) 
    } 
})(jQuery); 

HTML标记:

<input id="txtTime" type="text" maxlength="4" onpaste="return false;" onchange="this.value = this.value.Timeset();" /> 

我怎样才能做到这一点?我的正则表达式也可能是这个的根源。请注意,我不想使用任何外部蒙版插件,因为我必须在这一个上应用hot-keys

回答

2

让我们试试这个:

function formatTime(s) { 
    return s.replace(/\D/g, "").replace(/^(\d\d)(\d\d).*$/, "$1:$2"); 
} 

(function ($) { 
    $.fn.timeInput = function() { 
     return $(this).change(function() { 
      $(this).val(formatTime($(this).val())) 
     }); 
    } 
})(jQuery); 

http://jsfiddle.net/LAbFQ/

+0

哇!这很酷。这就是我想要的。嘿有没有任何表达限制用户不要超过** 23:59 **? –

+0

@DKM:是的,有,但对于评论来说太复杂了;) – georg

+0

好吧,谢谢你的时间。 :) –