需要限制键盘的最大值

时间:2017-04-04 06:14:07

标签: angularjs html5

下面是我正在尝试的HTML代码,我可以通过使用向上和向下键来限制数字大于5。但我需要限制键盘手动输入。在目前的情况下,我们可以通过键盘给出任何数字并且它正在接受。

  <input type="number" max="5" min="1">

1 个答案:

答案 0 :(得分:0)

这段代码用最大数字代替输入的数字,显示最大数字(如果输入的数字大于最大数字)

<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>
    <div ng-app="app" ng-controller="controller">

        <h4> Prevent typing value greater than max (i.e 100):
        <input type="number" min="1" max="100" limit-to-max />
        <script type="text/javascript">
        var app = angular.module("app", []);

        app.controller("controller", function($scope) {

        });

        app.directive("limitToMax", function() {
            return {
                link: function(scope, element, attributes) {
                    element.on("keydown keyup", function(e) {
                        if (Number(element.val()) > Number(attributes.max) &&
                            e.keyCode != 46 // delete
                            &&
                            e.keyCode != 8 // backspace
                        ) {
                            e.preventDefault();
                            element.val(attributes.max);
                        }
                    });
                }
            };
        });
        </script>
    </div>
</body>

</html>
相关问题