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
1 Answer
Reset to default 4Well, two things:
- First, you have to instantiate your function:
vm.setCapacityType = function(e) {
- 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
版权声明:本文标题:javascript - Ng-keypress prevent default for specific charCode - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742392110a2466193.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论