TinyMCE HTML Character Count

I was working on an application recently, integrating the tinyMCE (wysiwyg) editor into all the text areas. We ran into a problem though because the application was using a MS SQL 2000 database which has a maximum row size of 8060 bytes. Which means that regardless of field type we can only enter up to approximately 8000 characters. In this instance I had 2 text areas i needed to limit to 2500 and 3000 characters respectfully, to ensure a safe buffer when adding the record to the database with the additional form data.

Examples provided by other users on the TinyMCE website with similar problems were patchy or overcomplicated for what I wanted to do:

  • Display an HTML character count for the user
  • Diplay the character count in the location where the HTML path indicator was located.
  • Turn the counter bold and red when the user has exceeded the allowed number of characters.

I muddled of it together myself referencing examples on the forum, but ran into a hurdle when I needed to set different editors with different character limits. Luckily I must have caught the TinyMCE developer in a good mood because he helped me polish off my solution.

You can read the thread here:

Below you’ll find a stripped down version of the TinyMCE editor with my custom function for doing the above. I’ve commented it alot so hopefully you’ll be able to read though this simple resolution and work out a version for yourself!

// General options
mode : "textareas",
theme_advanced_path : false, //hide the path info
charLimit : 3000, // this is a default value which can get modified later
//set up a new editor function 
setup : function(ed) {
 //peform this action every time a key is pressed
 ed.onKeyUp.add(function(ed, e) {
 //define local variables
 var tinymax, tinylen, htmlcount;
 //manually setting our max character limit
 tinymax = ed.settings.charLimit;
//grabbing the length of the curent editors content
 tinylen = ed.getContent().length;
//setting up the text string that will display in the path area
 htmlcount = "HTML Character Count: " + tinylen + "/" + tinymax;
 //if the user has exceeded the max turn the path bar red.
 if (tinylen>tinymax){
  htmlcount = "<span style='font-weight:bold; color: #f00;'>" + htmlcount + "</span>"
 //enable to override the limit for various editors here
 //tinyMCE.editors["mytextarea1"].settings.charLimit = 3000; 
 //this line writes the html count into the path row of the active editor
 tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + '_path_row'), htmlcount);  
Spread the love

About the author

Jill of everything master of nothing. Digital Communications Specialist, Graphic Designer, Web Designer, Developer, Artist, Marketer, Trainer & Writer.