我使用这个jQuery代码,只允许在输入文本字段中输入数字。如何仅使用jQuery在输入文本字段中允许数字(即使在复制粘贴时)?
jQuery(document).ready(function() {
jQuery('.only_numbers').keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
((e.keyCode === 65) && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(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();
}
});
});
这工作正常,除了一个小问题。它不允许在该领域粘贴任何东西。我如何允许用户在字段中粘贴字符串,只要字符串包含所有数字字符?
此外,如果我可以对输入文本字段只允许使用字母表做同样的操作,那将会很棒。
我不想使用,因为在浏览器的兼容性,造型和制作表单字段粘性问题'类型=“数字”'限制其他键。 – user1543784
但它在所有现代浏览器中得到广泛支持。 http://caniuse.com/#feat=input-number – Manish
检查我更新的答案它使用'type = text'验证这两种类型,并且支持IE和Firefox以及其他浏览器。 – Manish