[英]Minus sign and dot clear input type number field with replace()
I use replace()
to remove non-numeric characters from an input field, like so: 我使用replace()
从输入字段中删除非数字字符,如下所示:
<input type="number" oninput="this.value = this.value.replace(/[^\\d]/g,'');">
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. 它运作良好,但是当我输入一些数字后跟一个减号或一个点(在Android上它必须是两个点)时,整个字段被清除。 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? 为什么会发生这种情况?
To clarify, I only want to allow [0-9], not other possibly numeric characters like [.-e]. 为了澄清,我只想允许[0-9],而不是像[。-e]这样的其他可能的数字字符。
Here's a solution: 这是一个解决方案:
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">
I took part of the cross-browser code from this answer: https://stackoverflow.com/a/585590/3514976 我从这个答案中获取了部分跨浏览器代码: https : //stackoverflow.com/a/585590/3514976
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.