对于<input type="number">元素,maxlength无效。如何限制该数字元素的最大长度?
当前回答
我以前遇到过这个问题,我使用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
其他回答
我知道已经有一个答案,但如果你想让你的输入行为完全像maxlength属性或尽可能接近,使用以下代码:
(function($) {
methods = {
/*
* addMax will take the applied element and add a javascript behavior
* that will set the max length
*/
addMax: function() {
// set variables
var
maxlAttr = $(this).attr("maxlength"),
maxAttR = $(this).attr("max"),
x = 0,
max = "";
// If the element has maxlength apply the code.
if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {
// create a max equivelant
if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
while (x < maxlAttr) {
max += "9";
x++;
}
maxAttR = max;
}
// Permissible Keys that can be used while the input has reached maxlength
var keys = [
8, // backspace
9, // tab
13, // enter
46, // delete
37, 39, 38, 40 // arrow keys<^>v
]
// Apply changes to element
$(this)
.attr("max", maxAttR) //add existing max or new max
.keydown(function(event) {
// restrict key press on length reached unless key being used is in keys array or there is highlighted text
if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
});;
}
},
/*
* isTextSelected returns true if there is a selection on the page.
* This is so that if the user selects text and then presses a number
* it will behave as normal by replacing the selection with the value
* of the key pressed.
*/
isTextSelected: function() {
// set text variable
text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return (text.length > 0);
}
};
$.maxlengthNumber = function(){
// Get all number inputs that have maxlength
methods.addMax.call($("input[type=number]"));
}
})($)
// Apply it:
$.maxlengthNumber();
假设您希望允许的最大值为1000—可以是键入的,也可以是使用旋转器的。
你可以使用以下方法限制微调器值: Type ="number" min="0" max="1000"
并且用javascript限制键盘输入的内容: onkeyup =“如果(方法(this.value) > 1000){。值= 1000;返回错误;}”
<input type="number" min="0" max="1000" onkeyup="if(parseInt(this.value)>1000){ this.value =1000; return false; }">
您可以指定min和max属性,这将只允许在特定范围内输入。
<!-- equivalent to maxlength=4 -->
<input type="number" min="-9999" max="9999">
然而,这只适用于旋转控制按钮。尽管用户可以输入大于允许的最大值的数字,但表单将不会提交。
截图来自Chrome 15
你可以在JavaScript中使用HTML5的oninput事件来限制字符的数量:
myInput.oninput = function () {
if (this.value.length > 4) {
this.value = this.value.slice(0,4);
}
}
另一种选择是为任何具有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 name="myinput_drs"
oninput="maxLengthCheck(this)"
type = "number"
maxlength = "3"
min = "1"
max = "999" />
<script>
// This is an old version, for a more recent version look at
// https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
function maxLengthCheck(object)
{
if (object.value.length > object.maxLength)
object.value = object.value.slice(0, object.maxLength)
}
</script>
更新: 您可能还希望防止输入任何非数字字符,因为object。Length对于数字输入来说是一个空字符串,因此它的长度为0。因此maxLengthCheck函数将不起作用。
解决方案: 看这个或这个例子。
演示-查看完整版本的代码在这里: http://jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/
更新2:下面是更新代码: https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
更新3: 请注意,允许输入超过一个小数点可能会导致数值混乱。
推荐文章
- 使伸缩项目正确浮动
- 形式内联内的形式水平在twitter bootstrap?
- 自定义元素在HTML5中有效吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 在网页上用鼠标模拟震颤(例如帕金森病)?
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何改变文本区域的边框颜色:焦点
- 我如何设置背景颜色为文本的宽度,而不是整个元素的宽度,使用CSS?
- 如何删除和清除所有的本地存储数据
- 强制打开“另存为…”弹出打开文本链接点击PDF在HTML
- 如何修改标签文本?
- 在HTML中还有其他有用的空格码吗,比如半空格的 , em-spaces, en-spaces等等?
- 输入触发器按钮单击