空格键输入使用regex.replace擦除数据

时间:2019-02-25 12:36:28

标签: jquery regex

我搜索了超过三天的解决方案。我发现了一个堆栈答案Stack Ans和他的JSFiddle JSFiddle,该百分比100%适用于台式机,99%适用于移动版。 示例代码:

<input type="text" class="numeric" />
$('.numeric').on('input', function (event) { 
   this.value = this.value.replace(/[^0-9]/g, '');
});

在移动设备中查看jsfiddle链接并自己进行测试, 测试案例:提供输入值12345,然后按spacebar twice removes 5,再按两次空格键removes 4。该如何解决?

以下代码在台式机浏览器中有效,而在移动浏览器中无效,因为无法识别键代码。

$(".numeric").on("keypress", function (event) {
   if ((event.which < 48 || event.which > 57)) event.preventDefault();
});

测试视频日志: Video Log Bug Report

1 个答案:

答案 0 :(得分:0)

I have found a solution to my problem,

$('.NumOnly').on('input', function (event) {
if (this.value.indexOf(' ') < 0) {
    this.value = this.value.trim().replace(/[^0-9]/g, '');
    if (!CheckLength(event.target.maxLength, $("#" + event.target.id).val())) {
        event.returnValue = false;
        return false;
    }
}
else this.value = this.value.trim();
});

I check the input value has space using indexOf(' '). If the result is >= 0 then trim() the value, else replace using regular expression based validation.