我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。

我如何使用jQuery做到这一点?


当前回答

这似乎牢不可破。

// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
    this.value = this.value.replace(/[^0-9\.]+/g, '');
    if (this.value < 1) this.value = 0;
});

// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
    return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});

其他回答

你可以使用一个简单的JavaScript正则表达式来测试纯数字字符:

/^[0-9]+$/.test(input);

如果输入是数字,则返回true,否则返回false。

或事件键码,简单使用如下:

     // Allow: backspace, delete, tab, escape, enter, ctrl+A and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) || 
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }

    var charValue = String.fromCharCode(e.keyCode)
        , valid = /^[0-9]+$/.test(charValue);

    if (!valid) {
        e.preventDefault();
    }

使用JavaScript函数isNaN,

if (isNaN($('#inputid').val()))

if (isNaN(document.getElementById('inputid').val()))

if (isNaN(document.getElementById('inputid').value))

更新: 这里有一篇很好的文章谈论它,但使用jQuery:限制输入在HTML文本框的数值

我对上面的答案有问题。它不包括数字键盘,如果一个按shift+数字的特殊符号也不应该显示。但是这个解没有考虑到它。

我在这篇文章中找到的最好的链接是: http://www.west-wind.com/weblog/posts/2011/Apr/22/Restricting-Input-in-HTML-Textboxes-to-Numeric-Values

我是stackoverflow的新手,所以我不知道我是否可以把更好的解决方案编辑到顶层。

内联:

<输入名称=“号码”onkeyup=“if”值=这个值。“>

不显眼的风格(使用jQuery):

$(“输入[name = "数量"]”).keyup(函数(e) { 如果(\ D / g.test (this.value)) { //从输入值中过滤非数字。 这一点。Value = this.value。替换(\ D / g,”); } }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <输入名称= "数量" >

下面是另一种方法。这也可以用于粘贴。[用于字母-数字验证]

//Input Validation
var existingLogDescription = "";

$('.logDescription').keydown(function (event) {
    existingLogDescription = this.value;

});


$('.logDescription').keyup(function () {
    if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
        alert("Log Description should contain alpha-numeric values only");
        this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
        this.value = existingLogDescription;
    }
});