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

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

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

Praveen Jeganathan报道

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


当前回答

根据CanIUse的数据,截至2015年10月,HTML5支持输入类型数字,全球浏览器的支持度高达88%以上。

<input type="number" step="0.01" min="0" name="askedPrice" id="askedPrice" />

这不是JQuery相关的解决方案,但优点是在手机上的Android键盘会对输入数字进行优化。

或者,也可以使用带有新参数"pattern"的输入类型文本。更多细节在HTML5规范。

我认为它比jquery解决方案更好,因为在这个问题中提供的jquery解决方案不支持千位分隔符。如果你能使用html5。

JSFiddle: https://jsfiddle.net/p1ue8qxj/

其他回答

请在脚本底部添加:

if(this.value.length == 1 && this.value == 0)
 this.value = "";

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

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

也允许负数

下面的代码也接受负数

HTML

<input type="text" name="myText" />

JS

var pastValue, pastSelectionStart, pastSelectionEnd;

$("input").on("keydown", function() {
    pastValue          = this.value;
    pastSelectionStart = this.selectionStart;
    pastSelectionEnd   = this.selectionEnd;
}).on("input propertychange", function() {

    if ( this.value.length > 0 && $.isNumeric(this.value) == false && this.value != '-' ) {
        this.value          = pastValue;
        this.selectionStart = pastSelectionStart;
        this.selectionEnd   = pastSelectionEnd;
    }
}).on('blur', function(){
        if(this.value == '-')
            this.value = '';
});

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

$(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;
            }
        });
    }); 

更新

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

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

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

jquery。数字插件

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

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

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

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

HTML 5

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