Introduction
In this article, I am going to demonstrate how to implement TinyMCE Rich text editor with the character limitation and its validation using JavaScript in your web page.
TinyMCE Rich text editor
TinyMCE Rich text editor is a text editor control. It allows formatting the text within the rich text area, such as you can set headings like <h1> to <h6>, set fonts as bold, italic, underline, and much more. You can even embed your code there in the HTML. It also provides such a great functionality like copy, paste, undo, redo, text selection within the text area etc. You also can use blocks, such as Div, pre, Paragraph and etc.
The TinyMCE Rich text editor also provides the functionality of character count and its validation. So, if you want to limit the number of allowed characters for TinyMCE editor, then you can do it using JavaScript.
Implimentation of TinyMCE Rich text editor
So, let's start the implimentation of TinyMCE Rich text editor. The following HTML code consists of TinyMCE Rich text HTML text area and simple buttons.
- <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>
To count the number of characters within text area, you need to assigned KeyUp event to the TinyMCE rich text editor control as shown above. It will call the above JS functions and it will return the count of the total characters from the text area.
Now, when you click on the HTML button, the onclick property will be fired and ValidateCharacterLength() function will be called. It will return the validation of the char in textarea.
Browser compatibility of TinyMCE Rich text editor
The HTML code created above is tested in the following browsers.
Interner Exploler, Mozila Firefox, Google Chrome, Safari Web Browser, and Opera.
NOTE
If you are using an older version of web-browser, you should update this to the latest version.
Summary
Tiny MCE is a very useful text editor with several functionalities for our web applications.