使用replace()减号和点清除输入类型编号字段 [英] Minus sign and dot clear input type number field with replace()
问题描述
我使用 replace()
从输入字段中删除非数字字符,如下所示:
I use replace()
to remove non-numeric characters from an input field, like so:
<input type="number" oninput="this.value = this.value.replace(/[^\d]/g,'');">
效果很好,但是当我输入一些数字后跟一个减号或一个点(在Android上它必须是两个点)时,整个字段被清除。这仅在输入类型设置为数字时发生,而不是在设置为文本时发生,但我需要数字来显示移动设备上的数字键盘。
It works well, but when I enter a few numbers followed by a minus sign or a dot (on Android it has to be two dots), the whole field is cleared. This only happens when the input type is set to "number", not when it's set to "text", but I need "number" to show the numeric keyboard on mobile.
为什么会发生这种情况?
Why could this happening?
为了澄清,我只想允许[0-9],而不是像[。-e]这样的其他可能的数字字符。
To clarify, I only want to allow [0-9], not other possibly numeric characters like [.-e].
推荐答案
这是一个解决方案:
function cancelEvent(event) {// cross-browser code
event.cancelBubble = true;
event.returnValue = false;
if(event.stopPropagation)
event.stopPropagation();
if(event.preventDefault)
event.preventDefault();
}
document.getElementById('testInput').addEventListener('keydown', function(event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;// cross-browser code
if(keyCode != 8 && (keyCode < 48 || keyCode > 57)){// excludes non-numeric inputs
cancelEvent(event);
}
});
document.getElementById('testInput').addEventListener('textInput', function(event) {
event = window.event || event;// cross-browser code
if(/[^0-9]/.test(event.data)) {
cancelEvent(event);
}
});
<input type="number" id="testInput">
我从这个答案中获取了部分跨浏览器代码: https://stackoverflow.com/a/585590/ 3514976
I took part of the cross-browser code from this answer: https://stackoverflow.com/a/585590/3514976
这篇关于使用replace()减号和点清除输入类型编号字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!