maxlength attribute of input in html does not work

2019-04-06 11:05发布

问题:

I got a simple input field which has a maxlength="2" attribute. The code looks like this below:

<input id="txtLoginName" maxlength="2">

It works fine on most Android devices. However, on the HTC One M7, it does not work. On this device, it just allows me to enter as many characters as I want.

Any suggestion? I think it should be a device specific issue so far.

Thanks in advance.

回答1:

Try this one:

var $input = $('input')
$input.keyup(function(e) {
    var max = 5;
    if ($input.val().length > max) {
        $input.val($input.val().substr(0, max));
    }
});


回答2:

I've noticed this issue on a couple of projects. I think certain versions of Android have bad support for maxlength.

My solution was to use a jQuery keydown function that checks the amount of characters and prevents anymore from being entered if the max has been hit.

$('#inputWithMaxLength').keydown(function (e) {

    var inputLength = jQuery(this).val().length;

    if(inputLength >= 10) {
        e.preventDefault();
        return false;
    }
}

I'm sure you could change this so that it searched for any input with attributes of maxlength and created a jQuery backup on the fly. I'm not sure if that would be rather slow though.