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

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


当前回答

下面是使用正则表达式的方法:

$('input').bind('keypress', function (event) {
var regex = new RegExp("^[0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
   event.preventDefault();
   return false;
}

});

https://jsfiddle.net/astrapi69/qbk2vjty/1/

你可以把正则表达式改成其他任何东西如果你想限制其他字符,然后是数字。

其他回答

需要确保你有数字键盘和tab键工作

 // Allow only backspace and delete
            if (event.keyCode == 46 || event.keyCode == 8  || event.keyCode == 9) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {

                }
                else {
                    event.preventDefault();
                }
            }

下面是一个使用jQuery UI小部件工厂的答案。您可以轻松地自定义允许的字符。

$('input').numberOnly({
    valid: "0123456789+-.$,"
});

这将允许数字、数字符号和美元金额。

$.widget('themex.numberOnly', {
    options: {
        valid : "0123456789",
        allow : [46,8,9,27,13,35,39],
        ctrl : [65],
        alt : [],
        extra : []
    },
    _create: function() {
        var self = this;

        self.element.keypress(function(event){
            if(self._codeInArray(event,self.options.allow) || self._codeInArray(event,self.options.extra))
            {
                return;
            }
            if(event.ctrlKey && self._codeInArray(event,self.options.ctrl))
            {
                return;
            }
            if(event.altKey && self._codeInArray(event,self.options.alt))
            {
                return;
            }
            if(!event.shiftKey && !event.altKey && !event.ctrlKey)
            {
                if(self.options.valid.indexOf(String.fromCharCode(event.keyCode)) != -1)
                {
                    return;
                }
            }
            event.preventDefault(); 
        });
    },

    _codeInArray : function(event,codes) {
        for(code in codes)
        {
            if(event.keyCode == codes[code])
            {
                return true;
            }
        }
        return false;
    }
});

下面是我使用的函数:

// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
            // home, end, period, and numpad decimal
            return (
                key == 8 || 
                key == 9 ||
                key == 13 ||
                key == 46 ||
                key == 110 ||
                key == 190 ||
                (key >= 35 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        });
    });
};

然后,您可以通过以下操作将其附加到控件:

$("#yourTextBoxName").ForceNumericOnly();

这是我用来验证整数或浮点值的数字输入(不显眼的jQuery风格):

$('input[name="number"]').keyup(function(e) { var float = parseFloat($(this).attr('data-float')); /* 2 regexp for validating integer and float inputs ***** > integer_regexp : allow numbers, but do not allow leading zeros > float_regexp : allow numbers + only one dot sign (and only in the middle of the string), but do not allow leading zeros in the integer part *************************************************************************/ var integer_regexp = (/[^0-9]|^0+(?!$)/g); var float_regexp = (/[^0-9\.]|^\.+(?!$)|^0+(?=[0-9]+)|\.(?=\.|.+\.)/g); var regexp = (float % 1 === 0) ? integer_regexp : float_regexp; if (regexp.test(this.value)) { this.value = this.value.replace(regexp, ''); } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" data-float="1" id="number" name="number" placeholder="integer"> <input type="text" data-float="0.1" id="number" name="number" placeholder="float">

$(document).ready(function()
{
    $("#textBoxId").bind("change",checkInput);
});

function checkInput()
{
    // check if $('#textBoxId').val() is under your constraints
    // then change its value, removing the last character
    // since this event will be called each time you
    // type a character
}