admin管理员组

文章数量:1336081

I have an input that is type="number". I want to prevent the user from typing decimals, addition, subtraction, or e into the input. Currently I am trying to e.preventDefault() on ng-keypress to disable the key pletely. But it is not working. I am using typescript and angularJs. It is seeing the event on keypress but it is not preventing the entry from being made. Or, would using ng-pattern with a regex be an alternative option retrict input to 0-9?

setCapacityType(e) {
  let keyCode = (e.keyCode ? e.keyCode : e.which);
  
  if (keyCode < 48 && keyCode > 57) {
    e.preventDefault();
    console.log("xx");
  }
}
<input type="number" ng-keydown="vm.setCapacityType($event)"
autoplete="off" autocorrect="off" spellcheck="false">

I have an input that is type="number". I want to prevent the user from typing decimals, addition, subtraction, or e into the input. Currently I am trying to e.preventDefault() on ng-keypress to disable the key pletely. But it is not working. I am using typescript and angularJs. It is seeing the event on keypress but it is not preventing the entry from being made. Or, would using ng-pattern with a regex be an alternative option retrict input to 0-9?

setCapacityType(e) {
  let keyCode = (e.keyCode ? e.keyCode : e.which);
  
  if (keyCode < 48 && keyCode > 57) {
    e.preventDefault();
    console.log("xx");
  }
}
<input type="number" ng-keydown="vm.setCapacityType($event)"
autoplete="off" autocorrect="off" spellcheck="false">

Share Improve this question asked Jul 19, 2016 at 15:52 Fritz-kriegFritz-krieg 511 gold badge1 silver badge6 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

Well, two things:

  1. First, you have to instantiate your function:
vm.setCapacityType = function(e) {
  1. To allows only numbers [0-9] you should write your condition as below:
if (keyCode < 48 || keyCode > 57) {

Now, you can have something like this:

 angular.module('app', [])
   .controller('mainCtrl', function() {
     var vm = this;

     vm.setCapacityType = function(e) {
       let keyCode = (e.keyCode ? e.keyCode : e.which);
       if (keyCode < 48 || keyCode > 57) {
         console.log("Prevent!");
         e.preventDefault();
       }
     }
   });
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare./ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl as main">
  <input type="text" ng-keydown="main.setCapacityType($event)" autoplete="off" autocorrect="off" spellcheck="false">
</body>

</html>

ng-pattern with a regex be an alternative option retrict input to 0-9?

No, ngPattern directive doesn't prevent/restrict the input.

本文标签: javascriptNgkeypress prevent default for specific charCodeStack Overflow