maxlength of input tag with type=text using html5

2020-05-03 13:08发布

i am able to enter more than specified maxlength of input tag with type=text using html5 in android webview. when lost focus/ blur, value will be trimmed to maxlength.

for example

<input type="text" maxlength="5" id="hahaha">

 value entered = abcdefghij
 on blur/lostfocus value displayed = abcde.

is there anyway that restricts the user from entering more characters than maxlength rather than trimming content after user entered the content . In IOS it is working fine.

3条回答
smile是对你的礼貌
2楼-- · 2020-05-03 13:36

A bit late to the party, but as neliojrr mentioned you can correct this using javascript/jquery. However, I would be very tempted to make this much more generic:

$('input[maxlength]').on('keydown', function(event) {
    var $this = $(this);
    if ($this.val().length > parseInt($this.attr('maxlength'), 10)) {
        event.preventDefault();
    }
});
查看更多
劳资没心,怎么记你
3楼-- · 2020-05-03 13:46

This problem probably is a bug in Android 4.1 version as you can see here 35264. You can solve that with some Javascript:

<input type="text" maxlength="3" id="hahaha" onkeypress="if(this.value.length >= this.getAttribute('maxlength') return false;" />

or JQuery:

$(function() {
    max_length = Number($("#hahaha").attr("maxlength"));
    $("#hahaha").attr("onkeypress", "if(this.value.length >= max_length) return false;");
});
查看更多
家丑人穷心不美
4楼-- · 2020-05-03 13:56

Thanks @paddybasi it worked for me. Just one small correction. keydown event doesn't seem to be working in android. So we need to change the event to "textInput".

$('input[maxlength],textarea[maxlength]').on('textInput', function (event) {
        var $this = $(this);
        if ($this.val().length >= parseInt($this.attr('maxlength'), 10)) {
            event.preventDefault();
        }
    });

查看更多
登录 后发表回答