Ruby-on-rails angularjs:只允许在文本框中输入数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16091218/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:49:58  来源:igfitidea点击:

angularjs: allows only numbers to be typed into a text box

javascriptruby-on-railsangularjsnumeric

提问by Ali Hasan

In angularjs is there any functionality available that allows only numbers to be typed into a text box like

在 angularjs 中是否有任何可用的功能只允许将数字输入到文本框中,例如

采纳答案by anazimok

This functionality just what you need. http://docs.angularjs.org/api/ng.directive:input.number

此功能正是您所需要的。http://docs.angularjs.org/api/ng.directive:input.number

EDIT:

编辑:

You can wrap the jquery plugin into directive. I created an example here: http://jsfiddle.net/anazimok/jTJCF/

您可以将 jquery 插件包装到指令中。我在这里创建了一个例子:http: //jsfiddle.net/anazimok/jTJCF/

HTML:

HTML:

<div ng-app="myApp">
    <div>
        <input type="text" min="0" max="99" number-mask="" ng-model="message">
            <button ng-click="handleClick()">Broadcast</button>
    </div>

</div>

CSS:

CSS:

.ng-invalid {
    border: 1px solid red;
}

JS:

JS:

// declare a module
var app = angular.module('myApp', []);

app.directive('numberMask', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).numeric();
        }
    }
});

回答by Anton

This code shows the example how to prevent entering non digit symbols.

此代码显示了如何防止输入非数字符号的示例。

angular.module('app').
  directive('onlyDigits', function () {

    return {
        restrict: 'A',
        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;
            });
        }
    };
});

回答by My Mai

HTML

HTML

 <input type="text" name="number" only-digits>

// Just type 123

// 只需输入 123

  .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9]/g, '');

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseInt(digits,10);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
});

// type: 123 or 123.45

// 类型:123 或 123.45

 .directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9.]/g, '');

            if (digits.split('.').length > 2) {
              digits = digits.substring(0, digits.length - 1);
            }

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseFloat(digits);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
 });

回答by samnau

I just used ng-keypress in the directive for my input.

我只是在指令中使用了 ng-keypress 进行输入。

HTML:

HTML:

<input type="text" ng-keypress="filterValue($event)"/>

JS:

JS:

$scope.filterValue = function($event){
        if(isNaN(String.fromCharCode($event.keyCode))){
            $event.preventDefault();
        }
};

回答by Sijan Gurung

This is the simplest and fastest way, for allowing the Number input only.

这是最简单和最快的方法,只允许数字输入。

<input type="text" id="cardno" placeholder="Enter a Number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' required>

Thanks

谢谢

回答by Craig

To build on Anton's answer a little --

以安东的回答为基础 -

angular.module("app").directive("onlyDigits", function ()
{
    return {
        restrict: 'EA',
        require: '?ngModel',
        scope:{
            allowDecimal: '@',
            allowNegative: '@',
            minNum: '@',
            maxNum: '@'
        },

        link: function (scope, element, attrs, ngModel)
        {
            if (!ngModel) return;
            ngModel.$parsers.unshift(function (inputValue)
            {
                var decimalFound = false;
                var digits = inputValue.split('').filter(function (s,i)
                {
                    var b = (!isNaN(s) && s != ' ');
                    if (!b && attrs.allowDecimal && attrs.allowDecimal == "true")
                    {
                        if (s == "." && decimalFound == false)
                        {
                            decimalFound = true;
                            b = true;
                        }
                    }
                    if (!b && attrs.allowNegative && attrs.allowNegative == "true")
                    {
                        b = (s == '-' && i == 0);
                    }

                    return b;
                }).join('');
                if (attrs.maxNum && !isNaN(attrs.maxNum) && parseFloat(digits) > parseFloat(attrs.maxNum))
                {
                    digits = attrs.maxNum;
                }
                if (attrs.minNum && !isNaN(attrs.minNum) && parseFloat(digits) < parseFloat(attrs.minNum))
                {
                    digits = attrs.minNum;
                }
                ngModel.$viewValue = digits;
                ngModel.$render();

                return digits;
            });
        }
    };
});

回答by Carlos Toledo

My solution accept Copy&Paste and save the position of the caret. It's used for cost of products so allows positive decimal values only. Can be refactor very easy to allow negative or just integer digits.

我的解决方案接受复制和粘贴并保存插入符号的位置。它用于产品成本,因此仅允许正十进制值。可以很容易地重构以允许负数或仅允许整数位。

angular
        .module("client")
        .directive("onlyNumber", function () {
            return {
                restrict: "A",
                link: function (scope, element, attr) {
                    element.bind('input', function () {
                        var position = this.selectionStart - 1;

                        //remove all but number and .
                        var fixed = this.value.replace(/[^0-9\.]/g, '');  
                        if (fixed.charAt(0) === '.')                  //can't start with .
                            fixed = fixed.slice(1);

                        var pos = fixed.indexOf(".") + 1;
                        if (pos >= 0)               //avoid more than one .
                            fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');  

                        if (this.value !== fixed) {
                            this.value = fixed;
                            this.selectionStart = position;
                            this.selectionEnd = position;
                        }
                    });
                }
            };
        });

Put on the html page:

放在html页面:

<input type="text" class="form-control" only-number ng-model="vm.cost" />

回答by Rohidas Kadam

Simply use HTML5

只需使用 HTML5

<input type="number" min="0"/>

回答by Leopoldo Sanczyk

This is the method that works for me. It's based in samnau anwserbut allows to submit the form with ENTER, increase and decrease the number with UPand DOWNarrows, edition with DEL,BACKSPACE,LEFTand RIGHT, and navigate trough fields with TAB. Note that it works for positive integers such as an amount.

这是对我有用的方法。它的总部设在samnau anwser但允许提交与形式ENTER,增加和减少与数量UP,并DOWN用箭头,编辑DELBACKSPACELEFTRIGHT,然后导航低谷中的字段TAB。请注意,它适用于正整数,例如金额。

HTML:

HTML:

<input ng-keypress="onlyNumbers($event)" min="0" type="number" step="1" ng-pattern="/^[0-9]{1,8}$/" ng-model="... >

ANGULARJS:

角度:

$scope.onlyNumbers = function(event){   
    var keys={
        'up': 38,'right':39,'down':40,'left':37,
        'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
        '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
    };
    for(var index in keys) {
        if (!keys.hasOwnProperty(index)) continue;
        if (event.charCode==keys[index]||event.keyCode==keys[index]) {
            return; //default event
        }
    }   
    event.preventDefault();
};

回答by igorGIS

Based on djsizsolution, wrapped in directive. NOTE: it will not handle digit numbers, but it can be easily updated

基于djsiz解决方案,包含在指令中。注意:它不会处理数字,但可以轻松更新

angular
        .module("app")
        .directive("mwInputRestrict", [
            function () {
                return {
                    restrict: "A",
                    link: function (scope, element, attrs) {
                        element.on("keypress", function (event) {
                            if (attrs.mwInputRestrict === "onlynumbers") {
                                // allow only digits to be entered, or backspace and delete keys to be pressed
                                return (event.charCode >= 48 && event.charCode <= 57) ||
                                       (event.keyCode === 8 || event.keyCode === 46);
                            }
                            return true;
                        });
                    }
                }
            }
        ]);

HTML

HTML

 <input type="text"
        class="form-control"
        id="inputHeight"
        name="inputHeight"
        placeholder="Height"
        mw-input-restrict="onlynumbers"
        ng-model="ctbtVm.dto.height">