【发布时间】:2015-06-13 00:01:20
【问题描述】:
【问题讨论】:
-
输入数字不强制用户输入数字,如果不是数字,它不会从表单返回任何内容。
标签: javascript jquery html
【问题讨论】:
标签: javascript jquery html
这会阻止用户输入任何不是数字的字符,同时仍然允许他们使用不可打印的键(ctrl、alt、退格、回车等)
本文第一部分来自this answer to a different question
第二部分基本上是在用户每次按键时检查,看那个键是否...
如果满足这两个条件,则阻止输入字符。
// https://stackoverflow.com/a/12467610/4639281
function printable(keycode) {
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
return !!valid;
}
// This part is me
document.getElementById('min').onkeydown = function(e) {
var char = String.fromCharCode(e.keyCode);
if(printable(e.keyCode) & isNaN(char)) {
e.preventDefault();
}
}
<input type="text" placeholder="Min." id="min">
【讨论】:
jquery numeric 插件成功了。谢谢大家的帮助。我不得不写更多的文字,因为答案至少应该是 30 个字符。
$(document).ready(function(){
$(".numeric").numeric();
});
【讨论】: