Minus sign and clear input type input field with replace ()

I am using replace()

to remove non-numeric characters from input field like:

<input type="number" oninput="this.value = this.value.replace(/[^\d]/g,'');">
      

Run codeHide result


This works well, but when I enter multiple numbers followed by a minus sign or a period (on Android it should be two dots) the entire field is cleared. This only happens when the input type is set to "number", not when it is set to "text", but I need "number" to show the numeric keypad on the mobile device.

Why could this happen?

To clarify, I only want to allow [0-9] and not other possibly numeric characters like [.-E].

+3


source to share


1 answer


Here's the 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">
      

Run codeHide result


I took part in cross-browser code from this answer: fooobar.com/questions/13976 / ...

+2


source







All Articles