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:
- If the 10 characters are full, even the arrow keys or ctrl+A wont work.
- Still able to copy paste more characters than 10.
- How can I allow only numbers depending on requirement?