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

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


当前回答

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

//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;
    }
});

其他回答

这将在添加非数字字符时保持先前的值。

$(document).on('input', '.digit-input', function() {
    var prevVal = $(this).attr('ov') ? $(this).attr('ov') : '';
    var newVal = this.value.replace(/[^0-9]/g, '');
    this.value = newVal != '' ? newVal : prevVal;
    $(this).attr('ov', this.value);
});

$(文件)。据(’input’'。digit-input',函数(){ var prevVal = $(this).attr('ov') ?$(this).attr('ov'): "; var newVal = this.value。回想起(^ [0 - 9]/ g '); this。= = " ? "newVal: prevVal; $ (this)。attr(’ov’this.value); }); < script " src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > / < script > <input type="text" class=" digital -input">

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

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

试试这个解决方案

您可以使用这个非常简单的解决方案来实现同样的目的

$(“input.numbers”).keypress(function(event) { 返回 /\d/.test(String.fromCharCode(event.keyCode)); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script> <输入类型=“文本” 类=“数字” 名称=“field_name” />

我参考了这个链接来获得解决方案。它工作得很完美!!

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

享受:

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);
});

您可以通过添加模式对文本输入使用HTML5验证。不需要使用regex或keyCodes手动验证。

<input type="text" pattern="[0-9.]+" />

$("input[type=text][pattern]").on("input", function () {
    if (!this.checkValidity())
        this.value = this.value.slice(0, -1);
});

可能,但对于输入[type=number]…

[type="number"]的问题是我们不能只删除最后的无效字符。当输入无效时,用户代理返回一个空字符串。

来自W3C HTML5规范:

如果元素的值不是有效的浮点数,则 将其设置为空字符串。

https://dev.w3.org/html5/spec-LC/number-state.html#number-state

这意味着我们需要一种方法来手动存储之前的输入值。

对于数字输入,解是这样的:

$("input[type=number], input[type=text][pattern]").on("input", function () {
    if (!this.checkValidity())
        this.value = $(this).data("current-valid") || "";
    else
        $(this).data("current-valid", this.value);
});

不幸的是,这将不能在IE和EDGE上工作。对于这些浏览器,我们需要使用上面的模式解决方案。然而,您仍然可以使用这个简单的填充数字输入。

$("input[type=number]").attr("type", "text").attr("pattern", "[0-9.]+");