最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set a maxLength of NUMBER input with jQuery - Stack Overflow

programmeradmin1浏览0评论

Sounds trivial, but it doesn't work for me... I tried to set a max length of NUMBER input, but it doesn't work. Your help is appreciated. Here's my code. Both don't work in Chrome

<input id="demo02" type="number">

$(document).ready(function(){
$("#demo02").attr('maxlength','2');
});

$(document).ready(function(){
$("#demo02").prop('maxlength','2');
});

Sounds trivial, but it doesn't work for me... I tried to set a max length of NUMBER input, but it doesn't work. Your help is appreciated. Here's my code. Both don't work in Chrome

<input id="demo02" type="number">

$(document).ready(function(){
$("#demo02").attr('maxlength','2');
});

$(document).ready(function(){
$("#demo02").prop('maxlength','2');
});
Share Improve this question edited Dec 28, 2017 at 22:10 Umesh .A Bhat 5873 gold badges15 silver badges27 bronze badges asked Dec 28, 2017 at 22:07 pappap 1331 gold badge3 silver badges14 bronze badges 2
  • 1 You cannot set maxlength for inputs of type number. – Tsvetan Ganev Commented Dec 28, 2017 at 22:10
  • 1 maxlength does not work on number inputs, only text, email, search, password, tel, or url developer.mozilla/en-US/docs/Web/HTML/Element/input – skyline3000 Commented Dec 28, 2017 at 22:11
Add a ment  | 

2 Answers 2

Reset to default 8

maxlength is not a valid attribute for input type="number".

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.

We will target the input elements of type number that have a max attribute set:

$('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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" max="99999">

Use max attribute to limit the highest available number. If you set max to 99, you can't go any higher.

$("#demo02").attr('max','99');

Or with plain Javascript:

document.getElementById('demo02').setAttribute('max', 99);

document.getElementById('demo02').setAttribute('max', 99);
<input id="demo02" type="number">

发布评论

评论列表(0)

  1. 暂无评论