0

I have the following code to limit characters in a content editable element.

$('div').on('keydown', function(event) {
  $('span').text('Total chars:' + $(this).text().length);
  if ($(this).text().length === 10 && event.keyCode != 8) {
    event.preventDefault();
  }
});
div {
  height: 100px;
  width: 300px;
  border: 1px solid grey;
  outline: 0;
}
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div contenteditable="true"></div>
<span></span>

https://jsfiddle.net/ableinfosoft/pw6L9j8u/1/

Problems:

  1. If the 10 characters are full, even the arrow keys or ctrl+A wont work.
  2. Still able to copy paste more characters than 10.
  3. How can I allow only numbers depending on requirement?
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Does this answer your question? [Limiting the number of characters in a ContentEditable div](https://stackoverflow.com/questions/2867479/limiting-the-number-of-characters-in-a-contenteditable-div) – Karan Dec 20 '22 at 08:07
  • @Karan, no it also has the same issues as I mentioned here. and the answer you suggested doesn't even show the character count. – AbleInfosoft Gmail Dec 20 '22 at 08:12
  • Change `&& event.keyCode != 8` to exclude all non-printing characters. – Barmar Dec 20 '22 at 08:20
  • Like in [this answer](https://stackoverflow.com/a/55274684/1491895) to the linked question. – Barmar Dec 20 '22 at 08:22

0 Answers0