一、输入框只能输入数字
原文:https://www.cnblogs.com/sese/p/5872144.html
分享下js限制输入框中只能输入数字的方法,包括整数与小数,分享几个例子,有需要的朋友参考下。
1.使用正则表达式限制输入框只能输入数字:
<input type="text" onkeyup="this.value=this.value.replace(/[^d]/g,'') " onafterpaste="this.value=this.value.replace(/[^d]/g,'') " name="f_order" value="1"/>
其中,onafterpaste防止用户从其它地方copy内容粘贴到输入框。
2.输入框只能输入字母和下横线的正则表达式
<input onkeyup="this.value=this.value.replace(/[^_a-zA-Z]/g,'')" onpaste="this.value=this.value.replace(/[^_a-zA-Z]/g,'')">
3.输入框只能输入字母数字和下横线的正则表达式
<input onkeyup="this.value=this.value.replace(/[^w]/g,'')" onpaste="this.value=this.value.replace(/[^w]/g,'')">
或者
<input onkeyup="this.value=this.value.replace(/[W]/g,'')" onpaste="this.value=this.value.replace(/[W]/g,'')">
二、自动获取焦点
<input autofocus="autofocus" id="input">
document.getElementById('input').focus();
三、禁止TAB键
scanBody是页面的外部DIV,禁止了响应tab,从而阻止input失去焦点
$("#scanBody").keydown(function (event) { if (event.keyCode == 9) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } });