我正在使用 Jquery Numeric插件,但我发现它不适用于 Osx 上的 FireFox 3.6(不允许粘贴)。
我正在搜索仅允许在输入文本字段上输入数字文本的 Jquery 插件或 Javascript 片段。
我有以下要求:
- 应该只允许数字文本
- 不应使用标点符号 (.,)
- 不应允许虚线文本 (-)
- 应该只允许粘贴数字文本
- 多浏览器
- 多平台
最佳答案
演示: http://so.devilmaycode.it/allowing-just-numeric-text-on-input-text-field/
jQuery.fn.onlyDigits = function() {
var k;
// little trick just in case you want use this:
$('<span></span>').insertAfter(this);
var $dText = $(this).next('span').hide();
// Really cross-browser key event handler
function Key(e) {
if (!e.which && ((e.charCode ||
e.charCode === 0) ? e.charCode: e.keyCode)) {
e.which = e.charCode || e.keyCode;
} return e.which; }
return $(this).each(function() {
$(this).keydown(function(e) {
k = Key(e);
return (
// Allow CTRL+V , backspace, tab, delete, arrows,
// numbers and keypad numbers ONLY
( k == 86 && e.ctrlKey ) || (k == 86 && e.metaKey) || k == 8 || k == 9 || k == 46 || (k >= 37 && k <= 40 && k !== 32 ) || (k >= 48 && k <= 57) || (k >= 96 && k <= 105));
}).keyup(function(e) {
var value = this.value.replace(/\s+/,'-');
// Check if pasted content is Number
if (isNaN(value)) {
// re-add stored digits if CTRL+V have non digits chars
$(this).val($dText.text());
} else { // store digits only of easy access
$dText.empty().append(value);
}
});
});
};
用法:
$("#onlydigits").onlyDigits();
注意:
thanks to Insider for pointing out the past (cmd+v) for MAC
按键事件处理程序REFERENCES:
- http://unixpapa.com/js/key.html
- http://www.hallvord.com/opera/keyevents.htm
- http://dev.opera.com/articles/view/keyboard-accessible-web-applications-3/
- http://qooxdoo.org/documentation/0.7/keyboard_events
- http://msdn.microsoft.com/en-us/library/ms533927(VS.85).aspx
- http://www.quirksmode.org/js/keys.html
- http://www.w3.org/2002/09/tests/keys-cancel2.html
关于javascript - 在输入文本字段上只允许数字文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2903806/