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

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


当前回答

没有一个答案在我的情况下工作,所以我在接受的答案做了一点改变,使它为动态添加的元素工作。

享受:

var inputFilter = function (elem, cb) {
    /*
    *    /^-?\d*$/               restricts input to integer numbers
    *    /^\d*$/                 restricts input to unsigned integer numbers
    *    /^[0-9a-f]*$/i          restricts input to hexadecimal numbers
    *    /^-?\d*[.,]?\d*$/       restricts input to floating point numbers (allowing both . and , as decimal separator)
    *    /^-?\d*[.,]?\d{0,2}$/   restricts input to currency values (i.e. at most two decimal places)
    */
    bdy.on('input keydown keyup mousedown mouseup select contextmenu drop', elem, function () {
        if (cb(this.value)) {
            this.oldValue = this.value;
            this.oldSelectionStart = this.selectionStart;
            this.oldSelectionEnd = this.selectionEnd;
        } else if (this.hasOwnProperty('oldValue')) {
            this.value = this.oldValue;
            this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
        }
    });
};

用法:

inputFilter('#onlyDigitsInput', function (val) {
    return /^\d*$/.test(val);
});

其他回答

这是我用来验证整数或浮点值的数字输入(不显眼的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">

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

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

<input type="number" name="quantity" min="0" max="9">
function validate_profile(frmid) {
    var form = $('#' + frmid);
    var error = $('.alert-danger', form);
    var success = $('.alert-success', form);
    form.validate({
        errorElement: 'span', //default input error message container
        errorClass: 'help-block', // default input error message class
        focusInvalid: true, // do not focus the last invalid input
        ignore: "",
        rules: {
            contact_no: {
                required: true,
                minlength: 10,
                maxlength: 10,
                number: true
            }, email_id: {
                required: true,
                email: true
            }
        },
        invalidHandler: function (event, validator) { //display error alert on form submit   
            success.hide();
            error.show();
            Metronic.scrollTo(error, -7000);
        },
        highlight: function (element) { // hightlight error inputs
            $(element)
                    .closest('.form-group').addClass('has-error'); // un set error class to the control group
            $(element)
                    .closest('.form-group').removeClass('has-success'); // set success class to the control group
        },
        unhighlight: function (element) { // revert the change done by hightlight
            $(element)
                    .closest('.form-group').removeClass('has-error'); // un set error class to the control group
            $(element)
                    .closest('.form-group').addClass('has-success'); // set success class to the control group
            error.hide();
        },
        success: function (label) {
            label.closest('.form-group').removeClass('has-error');
            label.closest('.form-group').addClass('has-success');
        },
        submitHandler: function (form) {
            success.show();
            error.hide();
            form.submit();
        }
    });
}
function Numbers(e)
{
    if($.browser.msie)
    {
        if(e.keyCode > 47 && e.keyCode < 58)
            return true;
        else
            return false;
    }
    else
    {
        if((e.charCode > 47 && e.charCode < 58) || (e.charCode == 0))
            return true;
        else
            return false;
    }
}

我希望这在所有浏览器上都能工作。

只需要在Jquery中应用此方法,您可以验证您的文本框只接受数字。

function IsNumberKeyWithoutDecimal(element) {    
var value = $(element).val();
var regExp = "^\\d+$";
return value.match(regExp); 
}

试试这个解决方案