对于<input type="number">元素,maxlength无效。如何限制该数字元素的最大长度?
当前回答
设置数字输入的maxlength的一个简单方法是:
<input type="number" onkeypress="return this.value.length < 4;" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />
其他回答
啊。就像有人在实施过程中半途而废,以为没人会注意到。
不管出于什么原因,上面的答案没有使用min和max属性。这个jQuery完成它:
$('input[type="number"]').on('input change keyup paste', function () {
if (this.min) this.value = Math.max(parseInt(this.min), parseInt(this.value) || 0);
if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value) || 0);
});
如果你是那种“jQuery-is-the-devil”类型,它也可能作为一个命名函数“oninput”使用jQuery。
更相关的属性是min和max。
另一种选择是为任何具有maxlength属性的东西添加一个侦听器,并将切片值添加到其中。假设用户不想在与输入相关的每个事件中使用函数。下面是一个代码片段。忽略CSS和HTML代码,JavaScript才是最重要的。
// Reusable Function to Enforce MaxLength function enforce_maxlength(event) { var t = event.target; if (t.hasAttribute('maxlength')) { t.value = t.value.slice(0, t.getAttribute('maxlength')); } } // Global Listener for anything with an maxlength attribute. // I put the listener on the body, put it on whatever. document.body.addEventListener('input', enforce_maxlength); label { margin: 10px; font-size: 16px; display: block } input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px } span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 } <label for="test_input">Text Input</label> <input id="test_input" type="text" maxlength="5"/> <span>set to 5 maxlength</span> <br> <label for="test_input">Number Input</label> <input id="test_input" type="number" min="0" max="99" maxlength="2"/> <span>set to 2 maxlength, min 0 and max 99</span>
<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" />
梅考·莫拉的回答是一个好的开始。 然而,他的解决方案意味着当您输入第二个数字时,所有字段的编辑都会停止。因此,您不能更改值或删除任何字符。
下面的代码停在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等等?
- 输入触发器按钮单击