有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
如果你想建议设备(可能是手机)在alpha和数值之间,你可以使用<input type="number">。
其他回答
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);"/ >
请记住地区差异(欧洲人使用句点和逗号的方式与美国人相反),加上负号(或将数字用括号括起来表示负数的习惯),加上指数符号(我正要谈到这个)。
现在大多数浏览器都支持type="number"这个属性
<input type="number" maxlength="3" ng-bind="first">
以下是我仅针对React用户的简单解决方案,我找不到更好的解决方案,所以我自己做了一个。3步骤。
首先,创建一个状态。
const [tagInputVal, setTagInputVal] = useState("");
然后,使用状态作为输入值(value={tagInputVal})并将事件传递给onChange处理程序。
<input id="tag-input" type="text" placeholder="Add a tag" value={tagInputVal} onChange={(e) => onChangeTagInput(e)}></input>
然后,在onChange处理程序中设置事件的值。
function onChangeTagInput(e) {
setTagInputVal(e.target.value.replace(/[^\d.]/ig, ""));
}
这也适用于波斯和阿拉伯数字:)
setNumericInput: function (event) {
var key = window.event ? event.keyCode : event.which
if (event.keyCode === 8 ||
(key >= 48 && key <= 57) ||
(key >= 1776 && key <= 1785)) {
return true
} else {
event.preventDefault()
}
}
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求