Enforcing the maxlength attribute on mobile browsers

mdurchholz picture mdurchholz · Jul 3, 2013 · Viewed 11.8k times · Source

I have an a text input with a maximum length:

<input type="text" name="name" maxlength="50">

This has been working fine on all the desktop browsers I've tried, but the maximum length does not seem to be enforced on mobile browsers.

Is there any way to get mobile browsers to enforce maxlength? I am open to using JavaScript and/or jQuery in the solution.

Answer

jedmao picture jedmao · Jul 3, 2013

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

jsFiddle here: http://jsfiddle.net/fttk2/1/