我正在使用以下javascript代码在日期字段中自动填充斜杠和冒号
的Javascript
var $dateField = jQuery('input[name='dateFieldId']');
//Bind keyup/keydown to the input
$dateField.bind('keyup', 'keydown', function (e) {
// if backspace, do nothing:
var thisVal;
var appender = '';
if (e.which !== 8) {
var numChars = $dateField.val().length;
// insert '/' after 2nd and 5th character is entered
if (numChars === 2 || numChars === 5) {
appender = '/';
}
// insert whitespace after 10th character is entered
else if (numChars === 10) {
appender = ' ';
}
// insert ':' after 13th character is entered
else if (numChars === 13) {
appender = ':';
}
}
thisVal = $dateField.val() + appender;
$dateField.val(thisVal);
});
HTML
<form:input size="26" type="text" class="form-control" name="dateFieldId" id="dateFieldId" path="dateFieldId" value="" placeholder="dd/mm/yyyy hh:mm" maxlength="16" />
这适用于台式机上的最新浏览器。但它在旧版Chrome浏览器和Chrome上的chrome / firefox失败了。一个问题是,当在日期字段中按下键时,焦点有时会丢失。另一个是它与斜线一起再次添加现有值
例如,当我键入'28'时,而不是'28 /'这是我的预期,它会在填充斜线后再次添加28,导致'28 / 280',如下所示
如果有人遇到过这个,请告诉我。我指的是以下帖子来做这件事 What's the best way to automatically insert slashes '/' in date fields