angularjs:仅允许html输入中的整数

时间:2018-06-08 05:06:40

标签: javascript angularjs



<md-input-container flex>
  <label>{{'COMMON.AMOUNT' | translate }}</label>
  <input class="margin-top-2" id="depositpaidamount" enterastab name="disabledamount" type="number" ng-model="deposit.paidamount" ng-disabled="true" />
</md-input-container>
&#13;
&#13;
&#13;

此字段也允许输入小数。但我想只输入整数。

3 个答案:

答案 0 :(得分:1)

如果输入的值是整数,则需要在JavaScript Controller中添加一个检查。

以下是工作代码:

&#13;
&#13;
Pulling from microsoft/dotnet

Pulling from microsoft/aspnetcore-build
&#13;
var invalidChars = ["-","+","e","."];

depositpaidamount.addEventListener("keydown", function(e) {
  if (invalidChars.includes(e.key)) {
    e.preventDefault();
  }
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在输入框中使用onkeypress事件

<input type="text" onkeypress='return (event.charCode >= 48 && event.charCode <= 57) || event.charCode <= 31'>

答案 2 :(得分:0)

使用指令

app.directive('restrictTo', function () {
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        var re = RegExp(attrs.restrictTo);
        var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;

        element[0].addEventListener('keydown', function (event) {
            if (!exclude.test(event.key) && !re.test(event.key)) {
                event.preventDefault();
            }
        });
    }
}
});

And In HTML we use following way:
<input type="text" restrict-to="[0-9]"/>
  

请参阅此处的Plunker示例..访问:https://plnkr.co/edit/PVjVgKOqZWojDJUYxKt4?p=preview

如果对您有用,请将其标记为答案。