-3

I want to restrict all characters entry except integer in to text box which I am using in angular 2 application , When user start typing other characters it should not show up in textbox ?

I tried out keyUp event , but doesn't seems to be working ?

<input type="text" id="txtEmpID" [(ngModel)]="filters.empID" class="form-control"
(keyup)="onKey($event)">


  onKey(event: any) {
        var charCode = event.keyCode;
         if (charCode > 95 && charCode < 106 ) { {
            console.log(charCode);
            return false;
        }
}

I cant use <input type="number" > as application uses IE9 and older browser which doesn't support these new HTML 5 standards . I know IE sucks

Dmehro
  • 1,269
  • 1
  • 16
  • 29
  • Check http://stackoverflow.com/questions/15554915/angular-directive-ignore-non-numeric-input – Wiktor Stribiżew Nov 28 '16 at 21:21
  • http://stackoverflow.com/a/19675023/5236174 – Lahar Shah Nov 28 '16 at 21:29
  • 1
    I got a bad feeling about this... If you are trying to restrict the key that can be used on the field please don't do that. I get mad when i can't copy, paste do `cmd+L`, `cmd+A` or any other key combination like navigating around with arrow keys... It get's never done properly. so just validate the value instead and show them when the input is wrong. see @LaharShah link how to do it more correct - Btw, i think you should screw ie9, it's less then 1% now – Endless Nov 28 '16 at 21:29

1 Answers1

0

After looking at all comments posted by everyone , i figured out a way to do so .

<input type="text" id="txtEmpID" [(ngModel)]="filters.empID" class="form-control" onkeypress="return event.charCode >= 48 && event.charCode <= 57">

Other way to do same thing is use input (keyup)="onKey($event)" event and write logic over there but there is a catch

if (isNaN(event.target.value)) {
  event.target.value = event.target.value.replace(/[^0-9]/g, '');
  console.log(event.target.value);
}

this code will do the job , when user enters any thing in textbox other than numbers it will cleared those values from textbox but when you try to retrieve filter box value in javascript it will show you old value which gets replaced using event.target.value.replace(/[^0-9]/g, '');(characters other than integer) . I am not sure if its specific to angular 2 or the other third party java script libraries which i am using .

Dmehro
  • 1,269
  • 1
  • 16
  • 29