我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(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">
其他回答
没有一个答案在我的情况下工作,所以我在接受的答案做了一点改变,使它为动态添加的元素工作。
享受:
var inputFilter = function (elem, cb) {
/*
* /^-?\d*$/ restricts input to integer numbers
* /^\d*$/ restricts input to unsigned integer numbers
* /^[0-9a-f]*$/i restricts input to hexadecimal numbers
* /^-?\d*[.,]?\d*$/ restricts input to floating point numbers (allowing both . and , as decimal separator)
* /^-?\d*[.,]?\d{0,2}$/ restricts input to currency values (i.e. at most two decimal places)
*/
bdy.on('input keydown keyup mousedown mouseup select contextmenu drop', elem, function () {
if (cb(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty('oldValue')) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
}
});
};
用法:
inputFilter('#onlyDigitsInput', function (val) {
return /^\d*$/.test(val);
});
下面是我使用的函数:
// 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();
用这种形式。在我看来,允许home, end, shift和ctrl这样的键是正确的,缺点是用户可以打印特殊字符:
$("#busca_cep").keydown(function(event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 13 || event.keyCode == 16 || event.keyCode == 36 || event.keyCode == 35) {
if (event.keyCode == 13) {
localiza_cep(this.value);
}
} else {
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
需要确保你有数字键盘和tab键工作
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {
}
else {
event.preventDefault();
}
}
这似乎牢不可破。
// 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));
});