基本上,我的页面上有一个数字输入字段,我希望用户只能在该字段中插入 4 数字。我知道我可以做这样的事情:
<input type="number" max="9999">
但是只有当我按下时,浏览器才会检查输入是否正确 “提交”按钮。我想要做的是:假设用户在框中键入“1234”,然后他尝试键入“1”或任何其他数字。我希望他不能那样做。基本上,当他一直按任何按钮/字母时,我希望它们不会出现在框中。
我怎样才能做到这一点?
最佳答案
var numberInput = document.getElementById('a');
numberInput.onkeypress = function(){
console.log(this.value.length)
if(this.value.length>3)
return false
}
<input id="a" type="number">
为了使其通用化,使用下面的代码
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
}
}
<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 2
关于javascript - 如何限制 html 数字输入(实时)中允许的数字数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31624902/