Javascript 文本输入只允许 angularjs 中的整数输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34013311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Text Input allow only Integer input in angularjs
提问by Cheetah Felidae
I want to set the html input[number] <input type="number" />
to allow only integerinput (not float).
我想将 html input[number] 设置<input type="number" />
为仅允许整数输入(不是浮点数)。
Basically, the html input[number] allow '.' to be entered for float input and I don't want that.
基本上,html input[number] 允许 '.' 为浮动输入而输入,我不希望那样。
Is there a quick way to accomplish it in AngularJS?
有没有一种快速的方法可以在 AngularJS 中完成它?
回答by Shyamal Parikh
Here is how this can be achieved.
这是如何实现的。
With input type - 'text'
Directive:
app.directive('onlyNumbers', function () { return { restrict: 'A', link: function (scope, elm, attrs, ctrl) { elm.on('keydown', function (event) { if(event.shiftKey){event.preventDefault(); return false;} //console.log(event.which); if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) { // backspace, enter, escape, arrows return true; } else if (event.which >= 48 && event.which <= 57) { // numbers 0 to 9 return true; } else if (event.which >= 96 && event.which <= 105) { // numpad number return true; } // else if ([110, 190].indexOf(event.which) > -1) { // // dot and numpad dot // return true; // } else { event.preventDefault(); return false; } }); } } });
HTML:
<input type="text" only-numbers>
With input type - 'number'
Directive:
app.directive('noFloat', function () { return { restrict: 'A', link: function (scope, elm, attrs, ctrl) { elm.on('keydown', function (event) { if ([110, 190].indexOf(event.which) > -1) { // dot and numpad dot event.preventDefault(); return false; } else{ return true; } }); } } });
HTML:
<input type="number" step="1" no-float>
输入类型 - 'text'
指示:
app.directive('onlyNumbers', function () { return { restrict: 'A', link: function (scope, elm, attrs, ctrl) { elm.on('keydown', function (event) { if(event.shiftKey){event.preventDefault(); return false;} //console.log(event.which); if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) { // backspace, enter, escape, arrows return true; } else if (event.which >= 48 && event.which <= 57) { // numbers 0 to 9 return true; } else if (event.which >= 96 && event.which <= 105) { // numpad number return true; } // else if ([110, 190].indexOf(event.which) > -1) { // // dot and numpad dot // return true; // } else { event.preventDefault(); return false; } }); } } });
HTML:
<input type="text" only-numbers>
输入类型 - 'number'
指示:
app.directive('noFloat', function () { return { restrict: 'A', link: function (scope, elm, attrs, ctrl) { elm.on('keydown', function (event) { if ([110, 190].indexOf(event.which) > -1) { // dot and numpad dot event.preventDefault(); return false; } else{ return true; } }); } } });
HTML:
<input type="number" step="1" no-float>
Check out the Plunker
查看Plunker
回答by Jinna Balu
Use pattern property:
使用模式属性:
<input type="number" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required>
<input type="number" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required>
please see the demo : https://jsfiddle.net/JBalu/vfbgrd5n/
请看演示:https: //jsfiddle.net/JBalu/vfbgrd5n/
may help.
可能有帮助。
回答by Yagnesh Khamar
I have looked for this many times, I had used directives in previous projects, but have finally founded a way that angular js provides by itself and hence can get rid of directives. Take a look at this code given at this link angularJs
我已经找了很多次了,我在以前的项目中使用过指令,但最终找到了一种 angular js 自己提供的方法,因此可以摆脱指令。看看这个链接angularJs给出的代码
The code shown there is as follows :
那里显示的代码如下:
<script>
angular.module('numberExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
value: 12
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Number:
<input type="number" name="input" ng-model="example.value"
min="0" max="99" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
Not valid number!</span>
</div>
<tt>value = {{example.value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
回答by Jilu_Simple_Powerfull_
(function () {
angular
.module('urModule').directive('numbersOnly', numbersOnly);
function numbersOnly() {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9]/g, '');
if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return undefined;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
}
})();
回答by AurA
Please find the fiddle http://jsfiddle.net/8a4sg0mo/
请找到小提琴 http://jsfiddle.net/8a4sg0mo/
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
function MyCtrl($scope) {
$scope.number = ''
}
It will allow only numbers to be entered, purely done using angular js.
它将只允许输入数字,完全使用 angular js 完成。
回答by ibrahim mohamed
Full working Sample:Custom DirectiveThe below works just fine
完整工作示例:自定义指令以下工作正常
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="AppCtrl">
<input type="text" allow-numbers-only />
<script>
var app = angular.module("myApp", []);
app.controller("AppCtrl", function($scope) {
$scope.title = "App"
})
app.directive("allowNumbersOnly", function() {
return {
restrict: "A",
link: function(scope, element, attrs) {
element.bind("keydown", function(event) {
if (event.keyCode == 8) {
return false;
} else if (!(event.keyCode > 47 && event.keyCode < 58) || event.shiftKey) {
event.preventDefault();
return false;
}
});
}
}
});
</script>
</body>
</html>
回答by Richard Hamilton
input[type=number]
by definition only accepts integers as input. Try it out yourself. Try typing in letters and it won't allow you.
input[type=number]
根据定义只接受整数作为输入。自己试试吧。尝试输入字母,它不会允许你。
There's no need for JavaScript as it's already built in. Did you perhaps mean input[type=text]
?
不需要 JavaScript,因为它已经内置了。您可能是说input[type=text]
?
You can accomplish that via angular directives. It would look something like this (not sure about my syntax though)
您可以通过角度指令来实现。它看起来像这样(虽然不确定我的语法)
app.directive('onlyNumbers', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind("keydown", function(event) {
if ((event.keyCode > 47 && event.keyCode < 58) && !event.shiftKey) {
event.preventDefault();
return false;
}
});
}
});
The syntax might have a few errors, but I will break down the basic formula.
语法可能有一些错误,但我会分解基本公式。
Since we are working with an input element, it makes sense that we use an attribute
directive. We can do this, by setting the restrict
property to A.
由于我们正在使用输入元素,因此使用attribute
指令是有意义的。我们可以通过将restrict
属性设置为 A来做到这一点。
Since we will be listening for keypress events, we should use the link
function. We want to listen for the keydown
event, to detect when a key is starting to be pressed.
由于我们将监听按键事件,我们应该使用该link
函数。我们想要监听keydown
事件,以检测何时开始按下某个键。
To find if the user typed a number, we will use keyCodes
, for which the number keys are 48 through 57 representing 0 through 9 respectively. However, we didn't account for special characters, which require hitting the number keys. So we make sure the shift key isn't being pressed either.
要查找用户是否键入了数字,我们将使用keyCodes
,其数字键为 48 到 57,分别代表 0 到 9。但是,我们没有考虑需要按数字键的特殊字符。因此,我们确保也没有按下 shift 键。
Then we can add this directive as an attribute on our input element.
然后我们可以将此指令作为属性添加到我们的 input 元素上。
<input type="text" only-numbers />