Can't prevent keyboard input on Android Chrome

Viewed 1247

so I want to prevent keyboard input when the user goes over a character limit in a contentEditable p tag:

<p autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true" placeholder="Enter text..." class="entry__text"></p>


$('.entry__text').on('keydown', function(e) {
    if (e.target.innerHTML.length > 10) {
        e.preventDefault();
        // return false;
    }
    console.log(e.target.innerHTML);
});

Either e.preventDefault() or return false; doesn't work. The condition is met, but keys still get written to the p tag. It does work on everything else except on newest Chrome on mobile Androids.

I tested in on a little bit older version (Chrome 40.0.2357.93 and then 51.xx), and it did prevent input.

Any suggestions?

1 Answers

Make the changes below to your code. I have added the maxlength attribute to your tag.

<p autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true" placeholder="Enter text..." maxlength="10" class="entry__text"></p>

Add the JavaScript code below:

$(document).ready(function() {

  var limitNum = 10;
  $("p[contenteditable='true'][maxlength]").on('keydown paste', function (event) {
     var cntMaxLength = parseInt($(this).attr('maxlength'));

     if ($(this).text().length === cntMaxLength && event.keyCode != 8) {
         event.preventDefault();
     }
  });
});

For your reference, check this JSFiddle.

Related