Bog*_* M. 4 html javascript html5 numbers input
基本上,我的页面上有一个数字输入字段,我希望用户只能在字段中插入4位数字.我知道我可以这样做:
<input type="number" max="9999">
Run Code Online (Sandbox Code Playgroud)
但是只有当我按下"提交"按钮时,浏览器才会检查输入是否正确.我想要做的是:假设用户在框中键入"1234",然后他尝试键入"1"或任何其他数字.我希望他不能那样做.基本上当他一直按下任何按钮/字母时,我希望它们不会出现在框中.
我怎样才能做到这一点?
var numberInput = document.getElementById('a');
numberInput.onkeypress = function(){
console.log(this.value.length)
if(this.value.length>3)
return false
}Run Code Online (Sandbox Code Playgroud)
<input id="a" type="number">Run Code Online (Sandbox Code Playgroud)
为了使其一般化,请使用下面的代码
var inputs = document.querySelectorAll('.restrictLength');
for( i in inputs){
inputs[i].onkeypress = function(){
console.log(this.id,this.value.length,this.getAttribute('data-restrict-to'));
if(this.value.length>Number(this.getAttribute('data-restrict-to'))-1)
return false
}
}Run Code Online (Sandbox Code Playgroud)
<input id="a" class="restrictLength" type="number" data-restrict-to="4"> restrict to 4
<br/>
<br/>
<input id="b" class="restrictLength" type="number" data-restrict-to="2"> restrict to 2Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
563 次 |
| 最近记录: |