当前位置: 代码迷 >> JavaScript >> 如何限制html号码输入(直播)中允许的数字量?
  详细解决方案

如何限制html号码输入(直播)中允许的数字量?

热度:17   发布时间:2023-06-03 17:43:43.0

基本上,我的页面上有一个数字输入字段,我希望用户只能在字段中插入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 

var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        $(function () {
            $("#a").bind("keypress", function (e) {
                if(this.value.length>3){ return false}
                var keyCode = e.which ? e.which : e.keyCode
                var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);

                return ret;
            });
            $("#a").bind("paste", function (e) {
                return false;
            });
            $("#a").bind("drop", function (e) {
                return false;
            });
        });

    <input id="a" type="number">
    <input type="number" id="userNumber">
        <input type="submit" id="numberSubmit" onclick="CheckValid()">
        <label id="warningMessage"></label>
        <script>
            function CheckValid(){
            var number = document.getElementById("userNumber").value;
            if(isNaN(number) || number.length != 4)
            {
                document.getElementById("warningMessage").innerHTML = "Invalid";
            }   
            else{
                document.getElementById("warningMessage").innerHTML = "Valid";
            }
            }
        </script>

甜美而简单。

<input id="a" type="text" maxLength = "4" 
onkeypress='return event.charCode > 48 && event.charCode < 57'>

注意:基于社区wiki的解决方案:

<input type="number" max="9999" maxlength="4">
  相关解决方案