我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
你可以尝试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
其他回答
我对上面的答案有问题。它不包括数字键盘,如果一个按shift+数字的特殊符号也不应该显示。但是这个解没有考虑到它。
我在这篇文章中找到的最好的链接是: http://www.west-wind.com/weblog/posts/2011/Apr/22/Restricting-Input-in-HTML-Textboxes-to-Numeric-Values
我是stackoverflow的新手,所以我不知道我是否可以把更好的解决方案编辑到顶层。
您可以使用这个非常简单的解决方案来实现同样的目的
$(“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” />
我参考了这个链接来获得解决方案。它工作得很完美!!
您可以使用以下代码。
<input type=“text” onkeypress=“return event.charCode >= 48 && event.charCode <= 57”>
下面是另一种方法。这也可以用于粘贴。[用于字母-数字验证]
//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;
}
});
使用JavaScript函数isNaN,
if (isNaN($('#inputid').val()))
if (isNaN(document.getElementById('inputid').val()))
if (isNaN(document.getElementById('inputid').value))
更新: 这里有一篇很好的文章谈论它,但使用jQuery:限制输入在HTML文本框的数值