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

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


当前回答

使用JavaScript函数isNaN,

if (isNaN($('#inputid').val()))

if (isNaN(document.getElementById('inputid').val()))

if (isNaN(document.getElementById('inputid').value))

更新: 这里有一篇很好的文章谈论它,但使用jQuery:限制输入在HTML文本框的数值

其他回答

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

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

试试这个解决方案

$(document).on("keypress", ".classname", function(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
});

如果有一个平滑的onlineer:

<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >

你可以尝试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

你可以像这样使用on input事件:

$(document).on("input", ".numeric", function() {
    this.value = this.value.replace(/\D/g,'');
});

但是,这个代码特权是什么?

它适用于移动浏览器(keydown和keyCode有问题)。 它也适用于AJAX生成的内容,因为我们使用了“on”。 比按下键更好的性能,例如在粘贴事件上。