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

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

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

Praveen Jeganathan报道

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


当前回答

我使用了James Nelli的答案,并添加了onpaste="return false;"(Håvard Geithus)以确保输入中只输入整数。即使你尝试粘贴,它也不会允许。

其他回答

这是我刚刚完成的一个代码片段(使用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的值

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

你看不到字母的神奇出现和消失的关键下来。这也适用于鼠标粘贴。

$('#txtInt').bind('input propertychange', function () {
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
});

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

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

我使用这个函数,它工作得很好

$(document).ready(function () {
        $("#txt_Price").keypress(function (e) {
            //if the letter is not digit then display error and don't type anything
            //if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 
            if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
                //display error message
                $("#errmsg").html("Digits Only").show().fadeOut("slow");
                return false;
            }
        });
    }); 

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

$(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]*$/);