Is there a workaround for text input maxlength not working in Safari?

14,079

Try this: HTML :

<input name="mytest" type="text">

Jquery :

$('input[name="mytest"]').keypress(function() {
    if (this.value.length >= 5) {
        return false;
    }
});
Share:
14,079
Medly
Author by

Medly

Java/C++ software engineer.

Updated on June 18, 2022

Comments

  • Medly
    Medly almost 2 years

    In safari version 8.0 (10600.1.25.1) on OS X 10.10.1 if you have the following:

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

    Fill it with 5 characters, and then position the caret (with the mouse or keyboard) somewhere in the middle of the string (not at the very beginning or end), typing will cause more characters to be entered.

    Specifically, it acts like it is ignoring the characters after the caret when calculating the "length" of the string, so if the caret was originally placed at position 1, 9 more characters will be enterable.

    This is not reproducible on the latest chrome or firefoxes.

    The effect can be seen on this page: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_input_maxlength

    Am I using maxlength wrong? Is this a known thing with workarounds? I've googled a bit with no joy...

  • larrydalmeida
    larrydalmeida almost 8 years
    This causes a bug in Firefox, once the maximum number of characters has been reached you can't use tab or [CTRL+A] and delete/backspace doesn't work. It stops all actions of printable and non printable characters.
  • toto21
    toto21 almost 8 years
    Indeed ! - So use keydown like this : $('input[name="mytest"]').keydown(function(e) { //alert(e.keyCode); if (e.keyCode != 8 && this.value.length >= 5) { return false; } });
  • toto21
    toto21 almost 8 years
    Better : test if browser is safari and version is < 9