什么是限制“数字”仅输入文本框的最佳方法?

我在找一些允许小数点的东西。

我看到很多这样的例子。但还没决定用哪一种。

Praveen Jeganathan报道

不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767


当前回答

我认为这是解决这个问题的好方法,而且非常简单:

$(function() {
    var pastValue, pastSelectionStart, pastSelectionEnd;

    $("input").on("keydown", function() {
        pastValue          = this.value;
        pastSelectionStart = this.selectionStart;
        pastSelectionEnd   = this.selectionEnd;
    }).on("input propertychange", function() {
        var regex = /^[0-9]+\.?[0-9]*$/;

        if (this.value.length > 0 && !regex.test(this.value)) {
            this.value          = pastValue;
            this.selectionStart = pastSelectionStart;
            this.selectionEnd   = pastSelectionEnd;
        }
    });
});

例如:JSFiddle

场景覆盖

这里的大多数类似建议至少不能满足其中一项要求,或者需要大量代码来覆盖所有这些场景。

只允许1个小数点。 允许home键、结束键和方向键。 允许在任何索引上使用删除和退格。 允许在任何索引处编辑(只要输入匹配正则表达式)。 允许使用ctrl+v和shift+insert进行有效输入(与右键单击+粘贴相同)。 不闪烁文本值,因为没有使用keyup事件。 恢复无效输入后的选择。

失败场景

从0.5开始,只删除0是不行的。这可以通过将正则表达式更改为/^[0-9]*\.?[0-9]*$/,然后添加一个模糊事件,当文本框以小数点开始时(如果需要)在0前面。请参阅此高级场景,以更好地了解如何修复此问题。

插件

我创建了这个简单的jquery插件,使这更容易:

$("input").limitRegex(/^[0-9]+\.?[0-9]*$/);

其他回答

作为对这个建议的轻微改进,您可以使用带有number()、digits和range方法的Validation插件。例如,下面的语句确保你得到一个0到50之间的正整数:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true,
      digits: true,
      range : [0, 50]
    }
  }
});

更新

有一个新的非常简单的解决方案:

它允许你对文本<input>, 包括各种数字滤波器。这将正确处理 复制+粘贴,拖放,键盘快捷键,上下文菜单操作, 不可输入键,以及所有键盘布局。

看看这个答案或者自己在JSFiddle上试试。

jquery。数字插件

我已经成功地实现了许多形式与jquery。数字插件。

$(document).ready(function(){
    $(".numeric").numeric();
});

此外,这也适用于文本区域!

但是,请注意,Ctrl+A,复制+粘贴(通过上下文菜单)和拖放将不能正常工作。

HTML 5

随着对HTML 5标准的广泛支持,我们可以为输入元素使用模式属性和数字类型来限制只输入数字。在一些浏览器(特别是谷歌Chrome)中,它也可以限制粘贴非数字内容。关于number和其他更新的输入类型的更多信息可以在这里找到。

有一个很好的jquery插件叫做jquery Mask plugin,设计用于在表单字段和html元素上做蒙版,但你也可以用它来简单地定义什么类型的数据可以在字段中输入:

$('.numeric-input').mask('0#');

现在只有数字将被允许在您的表单字段。

保持插入符号在输入中的位置的其他方法:

$(document).ready(function() {
  $('.numbersOnly').on('input', function() {
    var position = this.selectionStart - 1;

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

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

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

优点:

用户可以使用方向键、退格键、删除键、… 当你想要粘贴数字的时候就可以了

Plunker:演示工作

此代码属于文本框中的字母限制,在按键事件时必须输入唯一数字验证。希望对你有所帮助

HTML标记:

<input id="txtPurchaseAmnt" style="width:103px" type="text" class="txt" maxlength="5" onkeypress="return isNumberKey(event);" />

函数onlyNumbers(key) {

        var keycode = (key.which) ? key.which : key.keyCode

        if ((keycode > 47 && keycode < 58) || (keycode == 46 || keycode == 8) || (keycode == 9 || keycode == 13) || (keycode == 37 || keycode == 39)) {

            return true;
        }
        else {
            return false;
        }
    }