Javascript MaxLength with contenteditable

Viewed 104

I want to restrict the users to enter max ten characters. I was able to do so, but when I select a text and try to replace it, I'm unable to do so. For Ex: If I highlight on the "mm" then I'm unable to replace it as the max length is 10. How can I do so while having the maxlength? Here is my js function:

$('div').on('keydown', function(event) {
  $('span').text('Total chars:' + $(this).text().length);
  if($(this).text().length === 10 && event.keyCode != 8) {
    event.preventDefault();
  }
});

enter image description here

1 Answers

use highlighted text length as parameter

$('div').on('keydown', function(event) {
  var selection = window.getSelection().getRangeAt(0);
  $('span').text('Total chars:' + $(this).text().length);
  if($(this).text().length === 10-selection && event.keyCode != 8) {
   event.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable="true">mm/dd/yyyy</div>
<span></span>

Related