maxlength attribute of input in html does not work on HTC One M7

Long Dao picture Long Dao · Jun 27, 2014 · Viewed 16.4k times · Source

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.

Answer

Kevin Sebastian Fernandez picture Kevin Sebastian Fernandez · Oct 7, 2015

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));
    }
});