我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
我把所有的答案结合在一起,得出了以下代码:
jQuery('#input_id', function(e){
// Allow: backspace, delete, tab, escape, enter
if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode === 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode === 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode === 88 && e.ctrlKey === true) ||
// Disallow several dots (allow 190 only if no dots found)
(e.keyCode === 190 && jQuery(this).val().indexOf('.') == -1) ||
// Bug in some Android devices where it is always 229
(e.keyCode === 229) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
此外,表单应该有autocomplete="off"。如果没有这个选项,你可能会在移动设备上遇到自动补全算法的问题。
其他回答
有一个难以置信的兼容性问题,使用按键来检测被按下的字符…参见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'只是在那里展示如何扩展它以用于额外的未来掩码/验证器。你可以添加或删除它,它不会破坏任何东西;-)
为这些额外杂乱的评论道歉,我使用的是我为这里的工作人员创建的模板。
希望这能有所帮助, 干杯
重构了已接受的答案,因此不再需要使用注释,因为我讨厌注释。这也更容易用茉莉花进行测试。
allowBackspaceDeleteTabEscapeEnterPress: function(event){
return ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) >= 0);
},
allowContorlAPress: function(event){
return (event.keyCode == 65 && event.ctrlKey === true)
},
allowHomeEndLeftRightPress: function(event){
return (event.keyCode >= 35 && event.keyCode <= 39)
},
theKeyPressedIsEditRelated: function (event) {
return (this.allowBackspaceDeleteTabEscapeEnterPress(event)
|| this.allowContorlAPress(event)
|| this.allowHomeEndLeftRightPress(event));
},
isNotFromTheNumKeyPad: function (event) {
return (event.keyCode < 96 || event.keyCode > 105);
},
isNotFromTopRowNumberKeys: function (event) {
return (event.keyCode < 48 || event.keyCode > 57);
},
theKeyIsNonNumeric: function (event) {
return (event.shiftKey
|| (this.isNotFromTopRowNumberKeys(event)
&& this.isNotFromTheNumKeyPad(event)));
},
bindInputValidator: function(){
$('.myinputclassselector').keydown(function (event) {
if(this.validateKeyPressEvent(event)) return false;
});
},
validateKeyPressEvent: function(event){
if(this.theKeyPressedIsEditRelated(event)){
return;
} else {
if (this.theKeyIsNonNumeric(event)) {
event.preventDefault();
}
}
}
我想帮点忙,我做了我的版本,onlyNumbers函数…
function onlyNumbers(e){
var keynum;
var keychar;
if(window.event){ //IE
keynum = e.keyCode;
}
if(e.which){ //Netscape/Firefox/Opera
keynum = e.which;
}
if((keynum == 8 || keynum == 9 || keynum == 46 || (keynum >= 35 && keynum <= 40) ||
(event.keyCode >= 96 && event.keyCode <= 105)))return true;
if(keynum == 110 || keynum == 190){
var checkdot=document.getElementById('price').value;
var i=0;
for(i=0;i<checkdot.length;i++){
if(checkdot[i]=='.')return false;
}
if(checkdot.length==0)document.getElementById('price').value='0';
return true;
}
keychar = String.fromCharCode(keynum);
return !isNaN(keychar);
}
只需添加输入标签“…输入……id="price" onkeydown="return onlyNumbers(event)"…"然后你就完成了;)
下面是我使用的函数:
// 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("#no_of").keypress(function(event){
//Allow only backspace and delete
if (event.keyCode != 46 && event.keyCode != 8) {
if (!parseInt(String.fromCharCode(event.which))) {
event.preventDefault();
}
}
});
jQuery("#no_of").keyup(function(e){
var temp_s= jQuery("#no_of").val();
var multiply_val= temp_s*10;
jQuery("#ex-r").html(multiply_val);
});