[英]How to set a maxLength of NUMBER input with jQuery
Sounds trivial, but it doesn't work for me... I tried to set a max length of NUMBER input, but it doesn't work. 听起来微不足道,但对我而言不起作用...我试图设置NUMBER输入的最大长度,但不起作用。 Your help is appreciated. 感谢您的帮助。 Here's my code. 这是我的代码。 Both don't work in Chrome 两者都无法在Chrome中使用
<input id="demo02" type="number">
$(document).ready(function(){
$("#demo02").attr('maxlength','2');
});
$(document).ready(function(){
$("#demo02").prop('maxlength','2');
});
maxlength
is not a valid attribute for input type="number"
. 对于input type="number"
maxlength
不是有效的属性。
With this in mind, we will use the valid max
attribute to get its value length and use it as a maxlength within an input
event listener. 考虑到这一点,我们将使用有效的max
属性获取其值的长度,并将其用作input
事件侦听器中的maxlength。
We will target the input
elements of type number
that have a max
attribute set: 我们将定位具有max
属性集的类型为number
的input
元素:
$('input[type=number][max]:not([max=""])')
Code Snippet: 代码段:
$(document).ready(function() { $('input[type=number][max]:not([max=""])').on('input', function(ev) { var $this = $(this); var maxlength = $this.attr('max').length; var value = $this.val(); if (value && value.length >= maxlength) { $this.val(value.substr(0, maxlength)); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="number" max="99999">
Use max
attribute to limit the highest available number. 使用max
属性限制最大可用数量。 If you set max
to 99
, you can't go any higher. 如果将max
设置为99
,则不能再提高了。
$("#demo02").attr('max','99');
Or with plain Javascript: 或使用纯Javascript:
document.getElementById('demo02').setAttribute('max', 99);
document.getElementById('demo02').setAttribute('max', 99);
<input id="demo02" type="number">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.