我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
在document.ready中添加以下代码
$('.class of text box').keyup(function ()
{
this.value = this.value.replace(/[^0-9]/g, '');
});
其他回答
$(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;
});
HTML5中的pattern属性指定了检查元素值的正则表达式。
<input type="text" pattern="[0-9]{1,3}" value="" />
注意:pattern属性适用于以下输入类型:文本、搜索、url、电话、电子邮件和密码。
[0-9]可以替换为任意正则表达式条件。 {1,3}表示可以输入1的最小值和3的最大值。
很多人在这里使用键码属性,这是不容易记住的。如果你没有语言环境问题,那么你可以简单地使用键,这实际上是用户键入的输入。
看这把小提琴
$("#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" />
然后查看下面的简单代码。
请注意,此示例还包含对十进制输入的验证。
对于这个问题,它不是必需的,所以您可以简单地删除大小写“。”以删除小数的条目。
您可以通过添加模式对文本输入使用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.]+");
这似乎牢不可破。
// 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));
});