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

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

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

Praveen Jeganathan报道

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


当前回答

使用按键事件

数组的方法

var asciiCodeOfNumbers = [48, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57]
$(".numbersOnly").keypress(function (e) {
        if ($.inArray(e.which, asciiCodeOfNumbers) == -1)
            e.preventDefault();
    });

直接法

$(".numbersOnly").keypress(function (e) {
        if (e.which < 48 || 57 < e.which)
            e.preventDefault();
    });

其他回答

你可以使用带有number()方法的Validation插件。

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true
    }
  }
});

这是我刚刚完成的一个代码片段(使用Peter Mortensen / Keith Bentrup的一部分代码),用于对文本字段进行整数百分比验证(jQuery是必需的):

/* This validates that the value of the text box corresponds
 * to a percentage expressed as an integer between 1 and 100,
 * otherwise adjust the text box value for this condition is met. */
$("[id*='percent_textfield']").keyup(function(e){
    if (!isNaN(parseInt(this.value,10))) {
        this.value = parseInt(this.value);
    } else {
        this.value = 0;
    }
    this.value = this.value.replace(/[^0-9]/g, '');
    if (parseInt(this.value,10) > 100) {
        this.value = 100;
        return;
    }
});

这段代码:

允许使用主数字键和数字键盘。 验证以排除shift数字字符(例如#,$,%等) 将NaN值替换为0 替换为100个大于100的值

我希望这能帮助到那些需要帮助的人。

最好的方法是在文本框失去焦点时检查它的上下文。

可以使用正则表达式检查内容是否为“数字”。

或者你也可以使用Validation插件,它基本上会自动完成。

更新

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

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

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

jquery。数字插件

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

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

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

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

HTML 5

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

只需通过parseFloat()运行内容。它将在无效输入时返回NaN。