In this article I will explain how to count the characters of TinyMCE Rich Text Editor and also implement Character Limit validation i.e. limit the number of allowed characters for TinyMCE editor using JavaScript.
Implement Character Count and Character Limit validation for TinyMCE editor using JavaScript
The below HTML Markup consists of an HTML TextArea and a HTML Button. The TinyMCE editor has been implemented for the HTML TextArea.
Counting the number characters typed in the TinyMCE Rich Text Editor
In order to the count the number of characters, a KeyUp event handler has been assigned to the TinyMCE editor. Inside the KeyUp event handler, the CountCharacters JavaScript function is called which returns the total count of the characters in the TinyMCE editor and is displayed using an HTML DIV.
Limiting the characters typed in the TinyMCE Rich Text Editor
When the Submit button is clicked, the ValidateCharacterLength JavaScript function is executed which internally calls the CountCharacters JavaScript function and then matches returned total character count value with the maximum allowed characters value.
<textarea id="txtTinyMCE" rows="2" cols="20"></textarea>
<br />
<div id="character_count">
</div>
<br />
<input type="submit" value="Submit" onclick="return ValidateCharacterLength();" />
<script type="text/javascript" src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script type="text/javascript">
window.onload = function () {
tinymce.init({
selector: 'textarea',
width: 400,
setup: function (ed) {
ed.on('keyup', function (e) {
var count = CountCharacters();
document.getElementById("character_count").innerHTML = "Characters: " + count;
});
}
});
}
function CountCharacters() {
var body = tinymce.get("txtTinyMCE").getBody();
var content = tinymce.trim(body.innerText || body.textContent);
return content.length;
};
function ValidateCharacterLength() {
var max = 20;
var count = CountCharacters();
if (count > max) {
alert("Maximum " + max + " characters allowed.")
return false;
}
return;
}
</script>
Screenshot
Demo
Downloads
Download Code