Angular JS中的仅数字文本框

时间:2016-05-31 09:31:04

标签: angularjs

我想只在我的Angular JS应用程序中创建textbox数字。 这是我的代码 - 的script.js

app.directive('numbersonly', function () {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs, ctrl) {
            elm.on('keydown', function (event) {
                if (event.which == 64 || event.which == 16) {
                    // to allow numbers  
                    return false;
                } else if (event.which >= 48 && event.which <= 57) {
                    // to allow numbers  
                    return true;
                } else if (event.which >= 96 && event.which <= 105) {
                    // to allow numpad number  
                    return true;
                } else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {
                    // to allow backspace, enter, escape, arrows  
                    return true;
                } else {
                    event.preventDefault();
                    // to stop others  
                    return false;
                }
            });
        }
    }
});

在UI上 -

 <input type="text" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" numbersonly required />

但文本框同时接受数字和字符。

4 个答案:

答案 0 :(得分:0)

如果没有必要使用您自己的实现,请尝试Angular's number type input

答案 1 :(得分:0)

您可以使用type=number

<input type="number" id="txtEmpAge" data-ng-model="newemployee.Age" class="form-control" required />

这只会在文本框中显示数字值。

答案 2 :(得分:0)

在我看来,最好的方法来实现 ,它也不允许用户将粘贴字符串复制到输入

&#13;
&#13;
<input type="number" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

使用以下代码段使输入字段仅接受0到9之间的字符。这将消除小数点指针。

<input type="number" onkeypress="return isNumKey(event)"/>

使用此功能触发按键。

  function isNumKey(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }