我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
/**
Makes the textbox to accept only numeric input
*/
(function($) {
$.fn.allowOnlyNumeric = function() {
/**
The interval code is commented as every 250 ms onchange of the textbox gets fired.
*/
// var createDelegate = function(context, method) {
// return function() { method.apply(context, arguments); };
// };
/**
Checks whether the key is only numeric.
*/
var isValid = function(key) {
var validChars = "0123456789";
var validChar = validChars.indexOf(key) != -1;
return validChar;
};
/**
Fires the key down event to prevent the control and alt keys
*/
var keydown = function(evt) {
if (evt.ctrlKey || evt.altKey) {
evt.preventDefault();
}
};
/**
Fires the key press of the text box
*/
var keypress = function(evt) {
var scanCode;
//scanCode = evt.which;
if (evt.charCode) { //For ff
scanCode = evt.charCode;
}
else { //For ie
scanCode = evt.keyCode;
}
if (scanCode && scanCode >= 0x20 /* space */) {
var c = String.fromCharCode(scanCode);
if (!isValid(c)) {
evt.preventDefault();
}
}
};
/**
Fires the lost focus event of the textbox
*/
var onchange = function() {
var result = [];
var enteredText = $(this).val();
for (var i = 0; i < enteredText.length; i++) {
var ch = enteredText.substring(i, i + 1);
if (isValid(ch)) {
result.push(ch);
}
}
var resultString = result.join('');
if (enteredText != resultString) {
$(this).val(resultString);
}
};
//var _filterInterval = 250;
//var _intervalID = null;
//var _intervalHandler = null;
/**
Dispose of the textbox to unbind the events.
*/
this.dispose = function() {
$(this).die('change', onchange);
$(this).die('keypress', keypress);
$(this).die('keydown', keydown);
//window.clearInterval(_intervalHandler);
};
$(this).live('change', onchange);
$(this).live('keypress', keypress);
$(this).live('keydown', keydown);
//_intervalHandler = createDelegate(this, onchange);
//_intervalID = window.setInterval(_intervalHandler, _filterInterval);
}
})(jQuery);
上面的$ plugin是从AjaxControlToolkit过滤器文本框extender.js编写的。
然而,有一个行为并没有从AjaxControlToolkit中借用,那就是当用户复制和粘贴任何非数字值时,onchange事件就会触发,文本框就会吞噬这些值。我检查了代码,发现这个onchange在每250ms之后被调用,这是一个性能打击,因此注释了这部分。
其他回答
您可以通过添加模式对文本输入使用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.]+");
你可以尝试HTML5数字输入:
<input type="number" value="0" min="0">
对于不兼容的浏览器,可以使用Modernizr和Webforms2。
我把所有的答案结合在一起,得出了以下代码:
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"。如果没有这个选项,你可能会在移动设备上遇到自动补全算法的问题。
内联:
<输入名称=“号码”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 " > < /脚本> <输入名称= "数量" >
$(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;
});