有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
你可以用以下方法替换Shurok函数:
$(".numeric").keypress(function() {
return (/[0123456789,.]/.test(String.fromCharCode(Event.which) ))
});
其他回答
有一个更简单的解决方案,之前没有人提到过:
inputmode="numeric"
阅读更多信息:https://css-tricks.com/finger-friendly-numerical-inputs-with-inputmode/
请记住地区差异(欧洲人使用句点和逗号的方式与美国人相反),加上负号(或将数字用括号括起来表示负数的习惯),加上指数符号(我正要谈到这个)。
使用这个DOM
<input type='text' onkeypress='validate(event)' />
这个脚本
function validate(evt) {
var theEvent = evt || window.event;
// Handle paste
if (theEvent.type === 'paste') {
key = event.clipboardData.getData('text/plain');
} else {
// Handle key press
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
}
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
我意识到这是一个旧帖子,但我认为这可以帮助到一些人。最近,我不得不将一个文本框限制在小数点后5位。在我的例子中,用户输入也必须小于0.1
<input type="text" value="" maxlength=7 style="width:50px" id="fmargin" class="formText" name="textfield" onkeyup="return doCheck('#fmargin',event);">
这里是doCheck函数
function doCheck(id,evt)
{
var temp=parseFloat($(id).val());
if (isNaN(temp))
temp='0.0';
if (temp==0)
temp='0.0';
$(id).val(temp);
}
这里是相同的函数,只是强制输入整数
function doCheck(id,evt)
{
var temp=parseInt($(id).val());
if (isNaN(temp))
temp='0';
$(id).val(temp);
}
希望这能帮助到别人
Use:
<script>
function onlyNumber(id){
var DataVal = document.getElementById(id).value;
document.getElementById(id).value = DataVal.replace(/[^0-9]/g,'');
}
</script>
<input type="text" id="1" name="1" onChange="onlyNumber(this.id);">
如果你想在按下键后更新一个值,你可以改变onChange为onKeypress, onKeyDown或onKeyup。但是事件onKeypress不会在任何浏览器中运行。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求