我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(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.inputPhone").keyup(function() {
    var jThis=$(this);
    var notNumber=new RegExp("[^0-9]","g");
    var val=jThis.val();

    //Math before replacing to prevent losing keyboard selection 
    if(val.match(notNumber))
    { jThis.val(val.replace(notNumber,"")); }
}).keyup(); //Trigger on page load to sanitize values set by server

这似乎牢不可破。

// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
    this.value = this.value.replace(/[^0-9\.]+/g, '');
    if (this.value < 1) this.value = 0;
});

// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
    return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});

很多人在这里使用键码属性,这是不容易记住的。如果你没有语言环境问题,那么你可以简单地使用键,这实际上是用户键入的输入。

看这把小提琴

$("#txt").on("keypress",function(e){ console.log("Entered Key is " + e.key); switch (e.key) { case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "0": case "Backspace": return true; break; case ".": if ($(this).val().indexOf(".") == -1) //Checking if it already contains decimal. You can Remove this condition if you do not want to include decimals in your input box. { return true; } else { return false; } break; default: return false; } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> Enter Value <input id="txt" type="text" />

然后查看下面的简单代码。

请注意,此示例还包含对十进制输入的验证。

对于这个问题,它不是必需的,所以您可以简单地删除大小写“。”以删除小数的条目。

如果你必须解决变音符和特殊字符,尝试使用这个:

$(this).on( 'keypress', function( e )
{
    // Ensure that it is a number and stop the keypress
    if (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) {
        e.preventDefault();
    }
});  

简短而甜蜜——即使在30多个答案之后,这一点永远不会得到太多关注;)

  $('#number_only').bind('keyup paste', function(){
        this.value = this.value.replace(/[^0-9]/g, '');
  });