有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
JavaScript
function validateNumber(evt) {
var e = evt || window.event;
var key = e.keyCode || e.which;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45) {
// input is VALID
}
else {
// input is INVALID
e.returnValue = false;
if (e.preventDefault) e.preventDefault();
}
}
你可以添加逗号,句号和减号(,.-)
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
HTML
<input type="text" onkeydown="validateNumber(event);"/ >
其他回答
一个使用jQuery和replace()而不是查看事件的简短而甜蜜的实现。keyCode或event.which:
$('input.numeric').live('keyup', function(e) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
只有一个小的副作用,输入的字母出现暂时和CTRL/CMD + A似乎表现有点奇怪。
下面的函数将检查每个输入字符是否为number。
numeric: value => {
let numset = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
console.log(numset.has(value.substring(value.length - 1, value.length)));
}
还有一个例子,对我来说很有用:
function validateNumber(event) {
var key = window.event ? event.keyCode : event.which;
if (event.keyCode === 8 || event.keyCode === 46) {
return true;
} else if ( key < 48 || key > 57 ) {
return false;
} else {
return true;
}
};
也附加到按键事件
$(document).ready(function(){
$('[id^=edit]').keypress(validateNumber);
});
和HTML:
<input type="input" id="edit1" value="0" size="5" maxlength="5" />
下面是一个jsFiddle的例子
你也可以比较输入值(默认情况下被视为字符串)和它本身被强制为数字,比如:
if(event.target.value == event.target.value * 1) {
// returns true if input value is numeric string
}
然而,你需要绑定到事件,如keyup等。
只是使用jQuery的另一个变体
$(".numeric").keypress(function() {
return (/\d/.test(String.fromCharCode(event.which) ))
});
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求