简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM