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

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

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

Praveen Jeganathan报道

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


当前回答

/* 这是我的跨浏览器版本 如何允许只有数字(0-9)在HTML输入框使用jQuery? * /

$("#inputPrice").keydown(function(e){
    var keyPressed;
    if (!e) var e = window.event;
    if (e.keyCode) keyPressed = e.keyCode;
    else if (e.which) keyPressed = e.which;
    var hasDecimalPoint = (($(this).val().split('.').length-1)>0);
    if ( keyPressed == 46 || keyPressed == 8 ||((keyPressed == 190||keyPressed == 110)&&(!hasDecimalPoint && !e.shiftKey)) || keyPressed == 9 || keyPressed == 27 || keyPressed == 13 ||
             // Allow: Ctrl+A
            (keyPressed == 65 && e.ctrlKey === true) ||
             // Allow: home, end, left, right
            (keyPressed >= 35 && keyPressed <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (e.shiftKey || (keyPressed < 48 || keyPressed > 57) && (keyPressed < 96 || keyPressed > 105 )) {
                e.preventDefault();
            }
        }

  });

其他回答

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

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;
        }
    }

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

如果希望限制输入(而不是验证),可以使用键事件。就像这样:

<input type="text" class="numbersOnly" value="" />

And:

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

这将立即让用户知道他们不能输入alpha字符等,而不是在验证阶段之后。

您仍然需要验证,因为输入可能是通过鼠标剪切和粘贴来填充的,也可能是通过表单自动补全程序填充的,这可能不会触发键事件。

这是我刚刚完成的一个代码片段(使用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插件,它基本上会自动完成。