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

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


当前回答

你可以使用一个简单的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();
    }

其他回答

使用下面简单的jQuery,在文本框中只允许数字字符。您不需要手动筛选所有特殊字符,因此不会有遗漏某些特殊字符的危险。这将只允许数字0-9:(将下面的代码放在document ready中,并根据您的数字文本字段类名更改类名。)

//Event of data being keyed in to textbox with class="numericField".
$(".numericField").keyup(function() {
    // Get the non Numeric char that was enetered
    var nonNumericChars = $(this).val().replace(/[0-9]/g, '');                                  
    // Now set the value in text box 
    $(this).val( $(this).val().replace(nonNumericChars, ''));    

});

在document.ready中添加以下代码

    $('.class of text box').keyup(function () 
    {
    this.value = this.value.replace(/[^0-9]/g, '');
    });  

这里有很多使用java Script或jQuery的好答案。

我将添加一个非常简单的方法来使用HTML5存档。

<input type="number" name="quantity" min="0" max="9">

为了更详细地说明#3的答案,我将执行以下操作(注意:仍然不支持通过键盘或鼠标粘贴操作):

$('#txtNumeric').keypress(
            function(event) {
                //Allow only backspace and delete
                if (event.keyCode != 46 && event.keyCode != 8) {
                    if (!parseInt(String.fromCharCode(event.which))) {
                        event.preventDefault();
                    }
                }
            }
        );

使用JavaScript函数isNaN,

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

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

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

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