我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
有一个难以置信的兼容性问题,使用按键来检测被按下的字符…参见quirksmode了解更多信息。
我建议使用keyup来创建过滤器,因为这样就可以使用$(element).val()方法来计算实际的通用字符。
然后你可以过滤掉任何非数字使用正则表达式,如:
替换(/ [^ 0 - 9]/ g,”);
这就解决了所有的问题,比如移动和粘贴问题,因为总是有一个键up,所以值总是会被求值(除非javascript被关闭)。
所以…把它变成JQuery…这是我正在写的一个未完成的插件,它叫做inputmask,完成后将支持更多的掩码。现在它有数字掩码工作。
开始了……
/**
* @author Tom Van Schoor
* @company Tutuka Software
*/
(function($) {
/**
* @param {Object}
* $$options options to override settings
*/
jQuery.fn.inputmask = function($$options) {
var $settings = $.extend( {}, $.fn.inputmask.defaults, $$options);
return this.each(function() {
// $this is an instance of the element you call the plug-in on
var $this = $(this);
/*
* This plug-in does not depend on the metadata plug-in, but if this
* plug-in detects the existence of the metadata plug-in it will
* override options with the metadata provided by that plug-in. Look at
* the metadata plug-in for more information.
*/
// o will contain your defaults, overruled by $$options,
// overruled by the meta-data
var o = $.metadata ? $.extend( {}, $settings, $this.metadata()) : $settings;
/*
* if digits is in the array 'validators' provided by the options,
* stack this event handler
*/
if($.inArray('digits', o.validators) != -1) {
$this.keyup(function(e) {
$this.val(stripAlphaChars($this.val()));
});
}
/*
* There is no such things as public methods in jQuery plug-ins since
* there is no console to perform commands from a client side point of
* view. Typically only private methods will be fired by registered
* events as on-click, on-drag, etc... Those registered events could be
* seen as public methods.
*/
// private method
var stripAlphaChars = function(string) {
var str = new String(string);
str = str.replace(/[^0-9]/g, '');
return str;
}
});
};
// static public functions
//jQuery.fn.inputmask.doSomething = function(attr) {
//};
// static public members
//jQuery.fn.inputmask.someStaticPublicMember;
// some default settings that can be overridden by either $$options or
// metadata
// If you need callback functions for the plug-in, this is where they get
// set
jQuery.fn.inputmask.defaults = {
validators : []
};
})(jQuery);
要使用它,只需这样做:
$('#someElementId').inputmask({
validators: ['digits','someOtherNotYetImplementedValidator']
});
'someOtherNotYetImplementedValidator'只是在那里展示如何扩展它以用于额外的未来掩码/验证器。你可以添加或删除它,它不会破坏任何东西;-)
为这些额外杂乱的评论道歉,我使用的是我为这里的工作人员创建的模板。
希望这能有所帮助, 干杯
其他回答
注:这是更新后的答案。下面的注释指的是一个老版本,混乱的关键代码。
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试试吧。
您可以通过添加模式对文本输入使用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.]+");
下面是我使用的函数:
// 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();
使用jquery数值。下面的函数允许小数和数值。 例子: $ (" # inputId”)。数值({allow: "."});
使用JavaScript函数isNaN,
if (isNaN($('#inputid').val()))
if (isNaN(document.getElementById('inputid').val()))
if (isNaN(document.getElementById('inputid').value))
更新: 这里有一篇很好的文章谈论它,但使用jQuery:限制输入在HTML文本框的数值