我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
注:这是更新后的答案。下面的注释指的是一个老版本,混乱的关键代码。
jQuery
自己在JSFiddle上试试。
没有原生的jQuery实现,但你可以过滤文本<input>的输入值,使用以下inputFilter插件(支持复制+粘贴,拖放,键盘快捷键,上下文菜单操作,不可键入的键,插入符号位置,不同的键盘布局,有效性错误消息,以及ie9以来的所有浏览器):
// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
$.fn.inputFilter = function(callback, errMsg) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function(e) {
if (callback(this.value)) {
// Accepted value
if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
$(this).removeClass("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
// Rejected value - restore the previous one
$(this).addClass("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
// Rejected value - nothing to restore
this.value = "";
}
});
};
}(jQuery));
你现在可以使用inputFilter插件来安装一个输入过滤器:
$(document).ready(function() {
$("#myTextBox").inputFilter(function(value) {
return /^\d*$/.test(value); // Allow digits only, using a RegExp
},"Only digits allowed");
});
将您喜欢的样式应用于输入错误类。这里有一个建议:
.input-error{
outline: 1px solid red;
}
有关更多输入过滤器示例,请参阅JSFiddle演示。还要注意,您仍然必须进行服务器端验证!
纯JavaScript(不含jQuery)
这实际上不需要jQuery,你也可以用纯JavaScript做同样的事情。请看这个答案。
HTML 5
HTML 5有一个本地的解决方案<input type="number">(参见规范),但请注意浏览器的支持不同:
大多数浏览器只在提交表单时验证输入,而在输入时不验证。 大多数移动浏览器不支持step、min和max属性。 Chrome(版本71.0.3578.98)仍然允许用户在字段中输入字符e和e。还有这个问题。 Firefox(版本64.0)和Edge (EdgeHTML版本17.17134)仍然允许用户在字段中输入任何文本。
自己去w3schools.com试试吧。
其他回答
内联:
<输入名称=“号码”onkeyup=“if”值=这个值。“>
不显眼的风格(使用jQuery):
$(“输入[name = "数量"]”).keyup(函数(e) { 如果(\ D / g.test (this.value)) { //从输入值中过滤非数字。 这一点。Value = this.value。替换(\ D / g,”); } }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <输入名称= "数量" >
这个jQuery代码可以过滤掉按住Shift, Ctrl或Alt时键入的字符。
$('#AmountText').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) { // if shift, ctrl or alt keys held down
e.preventDefault(); // Prevent character input
} else {
var n = e.keyCode;
if (!((n == 8) // backspace
|| (n == 46) // delete
|| (n >= 35 && n <= 40) // arrow keys/home/end
|| (n >= 48 && n <= 57) // numbers on keyboard
|| (n >= 96 && n <= 105)) // number on keypad
) {
e.preventDefault(); // Prevent character input
}
}
});
下面是我使用的函数:
// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
然后,您可以通过以下操作将其附加到控件:
$("#yourTextBoxName").ForceNumericOnly();
你可以使用一个简单的JavaScript正则表达式来测试纯数字字符:
/^[0-9]+$/.test(input);
如果输入是数字,则返回true,否则返回false。
或事件键码,简单使用如下:
// Allow: backspace, delete, tab, escape, enter, ctrl+A and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
var charValue = String.fromCharCode(e.keyCode)
, valid = /^[0-9]+$/.test(charValue);
if (!valid) {
e.preventDefault();
}
使用JavaScript函数isNaN,
if (isNaN($('#inputid').val()))
if (isNaN(document.getElementById('inputid').val()))
if (isNaN(document.getElementById('inputid').value))
更新: 这里有一篇很好的文章谈论它,但使用jQuery:限制输入在HTML文本框的数值