2

I want to replace all my non numeric characters with an empty string. I found this solution

I am trying to replace the value of an input element on change. But when I use above, it is not replacing until I press a number.

Each non-digit I type stays until I type a digit

Ex: 2aaaaa will not be replaced. But as soon as 2aaaa3 is typed it will replace all the a's and it becomes 23

Is this the normal behaviour? How can I achieve my requirement.

component.ts

mobileChanged = () => {
    this.mobile = this.mobile.replace(/\D/g,'');
  };

angular component.html

<input type="text" [(ngModel)]="mobile" (ngModelChange)="mobileChanged()">
bula
  • 8,719
  • 5
  • 27
  • 44

2 Answers2

1

You can use keyup from jQuery or onkeyup from Javascript.

$("document").ready(function() {
  $("input").keyup(function() {
    let v = this.value.replace(/\D/g, '');
    this.value = v;
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" />
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29
0

Yes, it's the usual behaviour for ngModelChange but seems you need onkeyup event here to replace Non-digits. Something like-

function mobileChanged() {
  var txtinput = document.getElementById("fname");
  var x = txtinput.value.replace(/\D/g,'');
  txtinput.value = x;
}
<input id ="fname" type='text' onkeyup="mobileChanged()">

See if you still have confusion: https://stackoverflow.com/a/46403258/1138192

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103