简体   繁体   English

使用replace()减号和点清除输入类型编号字段

[英]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.

相关问题 输入数字掩码-防止减号 - input number mask - prevent minus sign 当语义ui中的输入类型编号反应时,禁止使用点,加号,减号,e - prohibit use dot,plus,minus,e when input type number in semantic ui react Angular 7 指令在 Android 电话上用于特殊字符点和减号的输入类型“数字”的 keydown 事件不会阻止 - Angular 7 directive with keydown event of input type “number” not prevent on Android phone for special character dot and minus 如何使用输入类型编号中的替换javascript删除点? - How to remove dot using replace javascript in input type number? 如何使用输入type = text字段仅接受数字,减号和小数,而Angular仅接受 - How to use an input type=text field to accept only digits, minus sign and decimals and nothing more with Angular 正则表达式使用 AngularJS 删除数字类型输入的加号和减号 - Regex to remove plus and minus sign of a number-type input using AngularJS 单击时在输入字段内添加/减去数字 - Add/minus number inside a input field on Click 输入数字类型美元符号 - Input Number Type Dollar Sign 这是使用值替换更新输入类型=数字字段的预期行为 - Which is the intended behaviour on update of input type=number field with value replace 如何用减号反转数字 - How to reverse number with minus sign
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM