maxlength属性对<input type="number">不起作用。这只发生在Chrome。
<input type="number" class="test_css" maxlength="4" id="flight_number" name="number"/>
maxlength属性对<input type="number">不起作用。这只发生在Chrome。
<input type="number" class="test_css" maxlength="4" id="flight_number" name="number"/>
当前回答
根据Neha Jain上面的回答,我只是把下面的代码添加到公共区域
$(':input[type="number"]').on('input', function() {
if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);
});
然后你可以像文本类型字段一样使用maxlength="4"。
其他回答
对于有长度限制的数字输入,您也可以尝试这种方法
<input type="tel" maxlength="4" />
如何限制输入类型的最大长度
<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,'');"
}
),
)
Chrome(技术上,Blink)将不会实现maxlength <input type="number">。
HTML5规范规定maxlength只适用于文本、url、电子邮件、搜索、电话和密码类型。
许多人张贴的onKeyDown()事件根本不工作,即你不能删除一旦你达到限制。因此,使用onKeyPress()而不是onKeyDown(),它工作得很好。
下面是工作代码:
用户将不允许输入超过4位数字 < br > <input type="number" pattern="/^-?\d+\.? "\d*$/" onKeyPress="if(this.value.length==4) return false;"/>