我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
这里有很多使用java Script或jQuery的好答案。
我将添加一个非常简单的方法来使用HTML5存档。
<input type="number" name="quantity" min="0" max="9">
其他回答
你可以像这样使用on input事件:
$(document).on("input", ".numeric", function() {
this.value = this.value.replace(/\D/g,'');
});
但是,这个代码特权是什么?
它适用于移动浏览器(keydown和keyCode有问题)。 它也适用于AJAX生成的内容,因为我们使用了“on”。 比按下键更好的性能,例如在粘贴事件上。
这似乎牢不可破。
// 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));
});
你可以尝试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
您可以通过添加模式对文本输入使用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.]+");
为什么这么复杂?你甚至不需要jQuery,因为有一个HTML5的模式属性:
<input type="text" pattern="[0-9]*">
最酷的是它在移动设备上显示了一个数字键盘,这比使用jQuery好多了。