简体   繁体   中英

maxlength=5 not working if input type=number

This is frustrating!

When the input type is text and I gave maxlength as 5, it is not allowing me to enter more than 5 characters

<input type="text"  maxlength="5" />

If I gave input type as number and I gave maxlength as 5, it is allowing more than 5 digits?

<input type="number" maxlength="5" pattern="[0-9]*" />

Am I missing something?

PS: This is for mobile responsive site!

Instead of maxlength use max

<input type="number" min="1" max="10000" />

Update

Small jQuery plugin

(function ($) {
    $.fn.maxlength = function (length) {
        return this.on('keydown', function () {
            var maxlength = length || parseInt($(this).attr('maxlength'), 10) ;
            if (maxlength && $(this).val().length >= maxlength) {
                $(this).val($(this).val().slice(0, maxlength - 1));
            }
        });
    };
}($));

Example

try using max ...

<input type="number" max="99999" />

EDIT : Showing Validation

<form id='FormValidation'>
<input id="myNum" type="number" min="1" max="99999" />
<input type="text"  maxlength="5" />
    <input type="submit" />
</form>

Try adding a number greater than 99999 and hitting submit, check the updated fiddle .

This jquery could help too...

$('#myNum').keyup( function(e){
    var max = $('#myNum').attr('max').length;
    if ($(this).val().length >= max) { 
        $(this).val($(this).val().substr(0, max));
    }
});

replace maxlength with max

 // Max Length = 5
<input type="number" max="99999" />
// length between 1 to 5
<input type="number" min="1" max="99999" />

Updated Answer. It's so simple!

<input type="number" id="nbr"/>

<input type="text"  maxlength="5" />

$(document).on('keypress','#nbr', function(e){
if($(this).val().length >= 5)
   {
       e.preventDefault();
   }

});

And you can add a max attribute that will specify the highest possible number that you may insert

<input type="number" max="999" />

if you add both a max and a min value you can specify the range of allowed values:

<input type="number" min="1" max="999" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM