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()">
4
  • Are you saying each non-digit you type stays until you type a digit? Can you provide any information about the field this happens with? Commented Dec 5, 2019 at 15:52
  • So what calls mobileChanged? Commented Dec 5, 2019 at 15:55
  • @epascarello updated Commented Dec 5, 2019 at 15:59
  • @bula I've added an answer for you, is that helped? Commented Dec 7, 2019 at 15:06

2 Answers 2

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="" />

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.