【问题标题】:Numeric only text box in Angular JSAngularjs中的数字文本框
【发布时间】:2016-05-31 09:31:03
【问题描述】:

我只想在我的 Angular JS 应用程序中将文本框设为数字。 这是我的代码- 脚本.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 />

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

【问题讨论】:

标签: angularjs


【解决方案1】:

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

【讨论】:

  • 好吧,我将输入类型更改为“数字”而不是“文本”,这没问题,但它接受十进制,这不是必需的。有什么帮助吗?
  • 请检查标签的模式属性。它允许您为输入指定一个正则表达式。
  • 我的意思是尝试这样的事情:
  • 虽然这可能是解决问题的宝贵提示,但答案确实需要比这更多的细节。请edit 提供示例代码来说明您的意思。特别是不要依赖链接来提供必要的内容;即使链接在任何时候都不可用,您的答案也应该仍然有用。
【解决方案2】:

您可以使用type=number

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

这将只接受文本框中的数字值。

【讨论】:

  • 和我做的一样,但它接受十进制,这不是必需的。有什么帮助吗?
  • 那么你应该使用指令来实现这一点。
【解决方案3】:

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

&lt;input type="number" onkeypress='return event.charCode &gt;= 48 &amp;&amp; event.charCode &lt;= 57'&gt;&lt;/input&gt;

【讨论】:

    【解决方案4】:

    使用以下 sn-p 使输入字段仅接受 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;
        }
    

    【讨论】:

    • 感谢@TobySpeight
    猜你喜欢
    • 1970-01-01
    • 2013-04-12
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多