Set max length for content editable element
It's pretty simple, on keydown
, count the length of element's string and prevent user if he tries to feed more than 100 chars
$('div').on('keydown paste', function(event) { //Prevent on paste as well
//Just for info, you can remove this line
$('span').text('Total chars:' + $(this).text().length);
//You can add delete key event code as well over here for windows users.
if($(this).text().length === 100 && event.keyCode != 8) {
event.preventDefault();
}
});
Demo
Explanation:
On keydown
or paste
event on the contenteditable
div
we check if the length
of the div
reached 100
and if user is not clicking backspace key than prevent user to feed in more characters by clicking any key or even pasting with right click.
This code does the job, note the "keyup" instead of "keydown" for correct processing of ctrl-v event, in addition, this code excludes arrow keys, finally please note the code that cut the text if you reach the limit:
$("div[contenteditable='true'][maxlength]").on('keyup paste', function (event) {
var cntMaxLength = parseInt($(this).attr('maxlength'));
if ($(this).text().length >= cntMaxLength && event.keyCode != 8 &&
event.keyCode != 37 && event.keyCode != 38 && event.keyCode != 39 &&
event.keyCode != 40) {
event.preventDefault();
$(this).html(function(i, currentHtml) {
return currentHtml.substring(0, cntMaxLength-1);
});
}
});
Then, in your html:
<div contenteditable="true" maxlength="1024"></div>
I did something like this by using the above mentioned answer to generalize the code, so that you can set the max length for any contenteditable div
$("div[contenteditable='true'][maxlength]").on('keydown paste', function (event) {
var cntMaxLength = parseInt($(this).attr('maxlength'));
if ($(this).text().length === cntMaxLength && event.keyCode != 8) {
event.preventDefault();
}
});
HTML will be as bewlow
<div id="IIYBAGWNBC" contenteditable="true" maxlength="500"></div>
this way you can mention the maxlenght to any of the contenteditable Div elemen. Hope this is helpful.