maxlength属性对<input type="number">不起作用。这只发生在Chrome。

<input type="number" class="test_css"  maxlength="4"  id="flight_number" name="number"/>

当前回答

试着用tel:

 maxlength="5" type="tel"

其他回答

如何限制输入类型的最大长度

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />

我有这个问题在django形式。这就是我解题的代码。

HTML

<input type="tel" maxlength="6" oninput="this.value=this.value.replace(/[-]/g,'');"></input> <!-- I needed to remove the "-" sinc tell field accepts it. -->

Django形式

class TokenForm(forms.Form):
code = forms.CharField(
    required=True,
    label="Enter 6 digit confirmation code",
    widget=forms.TextInput(
        attrs={
            "class": "form-control",
            "placeholder": "Enter 6 digit code",
            "type": "tel",
            "maxlength":"6", 
            "oninput":"this.value=this.value.replace(/[-]/g,'');"
        }
    ),
)

<input type=“number” min=“1” onKeyPress=“if(this.value.length==5) 返回 false”/>

使用类型数字与min和处理max与onKeyPress

<input type="number" min="1" onKeyPress="if(this.value.length==5) return false"/>

对于有长度限制的数字输入,您也可以尝试这种方法

<input type="tel" maxlength="4" />

试着用tel:

 maxlength="5" type="tel"