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

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


当前回答

我在我们的内部common js文件中使用了这个。我只是将类添加到需要这种行为的任何输入中。

$(".numericOnly").keypress(function (e) {
    if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});

其他回答

你可以尝试HTML5数字输入:

<input type="number" placeholder="enter the number" min="0" max="9">

这个输入标记元素现在只接受0到9之间的值 min属性设置为0,Max属性设置为9。

欲了解更多信息,请访问http://www.w3schools.com/html/html_form_input_types.asp

这就是我最近写这篇文章的原因。我知道这个问题已经有人回答了,但我把它留到以后使用。

该方法只允许0-9键盘和numpad,退格,制表符,左右箭头(正常形式操作)

$(".numbersonly-format").keydown(function (event) {
    // Prevent shift key since its not needed
    if (event.shiftKey == true) {
        event.preventDefault();
    }
    // Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete
    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
        // Allow normal operation
    } else {
        // Prevent the rest
        event.preventDefault();
    }
});

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

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

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

使用jQuery.validate做一些相当简单的事情

$(document).ready(function() {
    $("#formID").validate({
        rules: {
            field_name: {
                numericOnly:true
            }
        }
    });
});

$.validator.addMethod('numericOnly', function (value) {
       return /^[0-9]+$/.test(value);
}, 'Please only enter numeric values (0-9)');

这是我不久前创建的一个快速解决方案。你可以在我的文章中了解更多:

http://ajax911.com/numbers-numeric-field-jquery/

$("#textfield").bind("keyup paste", function(){
    setTimeout(jQuery.proxy(function() {
        this.val(this.val().replace(/[^0-9]/g, ''));
    }, $(this)), 0);
});