对于<input type="number">元素,maxlength无效。如何限制该数字元素的最大长度?
当前回答
<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />
或者如果你想什么都不能输入
<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />
其他回答
我以前遇到过这个问题,我使用html5数字类型和jQuery的组合解决了它。
<input maxlength="2" min="0" max="59" name="minutes" value="0" type="number"/>
脚本:
$("input[name='minutes']").on('keyup keypress blur change', function(e) {
//return false if not 0-9
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}else{
//limit length but allow backspace so that you can still delete the numbers.
if( $(this).val().length >= parseInt($(this).attr('maxlength')) && (e.which != 8 && e.which != 0)){
return false;
}
}
});
我不知道这些活动是否有点过分,但它解决了我的问题。 JSfiddle
HTML输入
<input class="minutesInput" type="number" min="10" max="120" value="" />
jQuery
$(".minutesInput").on('keyup keypress blur change', function(e) {
if($(this).val() > 120){
$(this).val('120');
return false;
}
});
<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />
或者如果你想什么都不能输入
<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />
下面是使用maxlength的最简单的解决方案:
<form>
<input class="form-control" id="code_pin" oninput="if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" maxlength="4">
</form>
梅考·莫拉的回答是一个好的开始。 然而,他的解决方案意味着当您输入第二个数字时,所有字段的编辑都会停止。因此,您不能更改值或删除任何字符。
下面的代码停在2,但允许继续编辑;
//MaxLength 2
onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"
推荐文章
- 使伸缩项目正确浮动
- 形式内联内的形式水平在twitter bootstrap?
- 自定义元素在HTML5中有效吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 在网页上用鼠标模拟震颤(例如帕金森病)?
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何改变文本区域的边框颜色:焦点
- 我如何设置背景颜色为文本的宽度,而不是整个元素的宽度,使用CSS?
- 如何删除和清除所有的本地存储数据
- 强制打开“另存为…”弹出打开文本链接点击PDF在HTML
- 如何修改标签文本?
- 在HTML中还有其他有用的空格码吗,比如半空格的 , em-spaces, en-spaces等等?
- 输入触发器按钮单击