#TinyMCE: Add Character Count

TinyMCE has a built in word counter but it does not have a way to count characters.  We have a requirement that limits the users to 5000 characters per textarea field.  This count is purely to keep the users from writing a book each time they enter data.  We only need to count the actual characters that the user sees, all html and hidden characters are ignored.

To do this I created a character count plugin.  It ended up pretty straight forward in the end.  I tried many different ways of pulling and counting the visible characters but many of them were pretty inaccurate.  This version is the closest I could get to the Microsoft Word character counts.

Factoids:

  • I started the plugin with a generic base similar to the existing TinyMCE word count plugin.
  • I layered on this Stack Overflow answer to decode the raw HTML in a way that gave me the most accurate character count.
  • I used this Stack Overflow answer to hide the the path in the status bar of the editor.
  • I also added a generic “Over 5000 characters” validation message that I turn on and off based on the validation done in the “on change” event.
  • The last piece was to validate the character count in the “on submit” event.
  • Thanks to the commenters who found some problems with this code!

TinyMCE Initialization



<pre>
    $('textarea.tinymce').tinymce({
      script_url: '/scripts/tinymce/4.0.25/tinymce.min.js',
      theme: "modern",
      plugins: "charactercount",
      toolbar: "bold italic | link | bullist numlist ",
      menubar: false,
      statusbar: true,
      setup: function (editor) {
        editor.on('change', function(e) {
          var count = this.plugins["charactercount"].getCount();
          if (count > 5000)
            $('#invalidContentHtml').show();
          else
            $('#invalidContentHtml').hide();
        });
      },
      init_instance_callback: function (editor) {
        $('.mce-tinymce').show('fast');
        $(editor.getContainer()).find(".mce-path").css("display", "none");
      }
    });
</pre>

Character Count Plugin:

tinymce.PluginManager.add('charactercount', function (editor) {
  var self = this;

  function update() {
    editor.theme.panel.find('#charactercount').text(['Characters: {0}', self.getCount()]);
  }

  editor.on('init', function () {
    var statusbar = editor.theme.panel && editor.theme.panel.find('#statusbar')[0];

    if (statusbar) {
      window.setTimeout(function () {
        statusbar.insert({
          type: 'label',
          name: 'charactercount',
          text: ['Characters: {0}', self.getCount()],
          classes: 'charactercount',
          disabled: editor.settings.readonly
        }, 0);

        editor.on('setcontent beforeaddundo', update);

        editor.on('keyup', function (e) {
            update();
        });
      }, 0);
    }
  });

  self.getCount = function () {
    var tx = editor.getContent({ format: 'raw' });
    var decoded = decodeHtml(tx);
    var decodedStripped = decoded.replace(/(<([^>]+)>)/ig, "").trim();
    var tc = decodedStripped.length;
    return tc;
  };

  function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
  }
});

On Submit Code:

var charcnt = tinyMCE.editors["{TextAreaId}"].plugins["charactercount"].getCount() <= 5000;

CSS Tweaks:

/* Optional: Adjust the positioning of the character count text. */
label.mce-charactercount {
margin: 2px 0 2px 2px;
padding: 8px;
}

/* Optional: Remove the html path code from the status bar. */
.mce-path {
    display: none !important;
}

** Updated on 10/28/15: Minor changes based on comments

javascript; Auto-highlight on focus

Sometimes I look online for code and when I find it I realize that I should have known how to do it. Then I feel silly. This is a time when that happened.

I needed to auto-highlight the contents of a read-only textbox or textarea when the user clicked on the input.  Easiest javascript I’ve implemented today!

StackOverflow answer…..

<input type="text" name="textbox" value="Test" onclick="this.select()" />

MVC: Disabling buttons on submit

Don’t want to lose this one.  Its some simple javascript that disables the submit buttons on form submission, from here.

$(document).on('invalid-form.validate', 'form', function () {
    var buttons = $('input[type="submit"]');
    setTimeout(function () {
        buttons.removeAttr('disabled');
    }, 1);
});
$(document).on('submit', 'form', function () {
    var buttons = $('input[type="submit"]');
    setTimeout(function () {
        buttons.attr('disabled', 'disabled');
    }, 0);
});

#TinyMCE: Plugin DDL with Popup

Recently I had a story asking for some advanced functionality for a new TinyMCE button. I broke down the requirements to the following.  I created a JSFiddle to show it working.

  • Custom TinyMCE drop down menu
  • When a menu item is selected it should insert the menu value into the editor at the cursor
  • Last item on the menu will show a popup
  • On the popup have a text box for entering custom text
  • When Insert is clicked insert the text into the editor at the cursor
Core plugin code – Javascript
$('#Insert').click(function () {
    var text = $('#added-token').val();
    tinyMCE.activeEditor.execCommand('mceInsertContent', false, &quot;{Added Text:&quot; + text + &quot;}&quot;);
    $('#token-modal').modal('hide');
    return false;
});
tinymce.PluginManager.add('tokens', function (editor, url) {
    editor.addButton('inserttoken', {
        title: &quot;Insert Token&quot;,
        type: 'menubutton',
        text: 'Tokens',
        icon: false,
        onselect: function (e) {
          if (e.control.settings.value != '{MenuItemPopup}') {
            editor.insertContent(e.control.settings.value);
          } else {
            $('#token-modal').modal({ show: true });
          }
        },
        menu: [
            { text: 'Menu Item 1', value: '{MenuItem1}' },
            { text: 'Menu Item 2', value: '{MenuItem2}' },
            { text: 'Menu Item 3', value: '{MenuItem3}' },
            { text: 'Menu Item 4', value: '{MenuItem4}' },                     
            { text: 'Menu Item with Popup', value: '{MenuItemPopup}' }                        
        ],
        onPostRender: function () {
            this.value('{MenuItem1}');
        }
    });    
});
tinymce.init({
    selector: &quot;textarea&quot;,
	width:      '100%',
	height:     270,
    plugins:    [ &quot;anchor link tokens&quot; ],
    statusbar:  false,
	menubar:    false,
    toolbar:    &quot;inserttoken anchor | alignleft aligncenter alignright alignjustify&quot;,
	rel_list:   [ { title: 'Lightbox', value: 'lightbox' } ]
});
Core plugin code – HTML
&lt;div id=&quot;token-modal&quot; class=&quot;modal hide fade&quot; &gt;
    &lt;div class=&quot;modal-header&quot;&gt;
        &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-hidden=&quot;true&quot;&gt;×&lt;/button&gt;
        &lt;h3 id=&quot;myModalLabel&quot;&gt;Modal header&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class=&quot;modal-body&quot;&gt;
        &lt;input type=&quot;text&quot; name=&quot;group&quot; id=&quot;added-token&quot;  /&gt;
    &lt;/div&gt;
    &lt;div class=&quot;modal-footer&quot;&gt;
        &lt;button data-dismiss=&quot;modal&quot;&gt;Close&lt;/button&gt;
        &lt;button id=&quot;Insert&quot;&gt;Insert&lt;/button&gt;
    &lt;/div&gt;

#TinyMCE: Disable/Enable Brute Force Solution

tinymceI spent a good chunk of yesterday trying to figure out how to change the state of the TinyMCE textbox from readonly to edit mode.  Or to set the values to enable and disable the box properly.  After much trial, error, and research I found this post which links to this post that explains that it is just not possible to do it cleanly.  These posts are a few years old but in the rest of my research I couldn’t find anything that contradicted them.  I tried many different workarounds suggested by other people and each one had something that just didn’t work quite right.  Here is the brute force solution that I came up with:

I created two TinyMCE editors one that is readonly and one that is not.  Then I show and hide them via a button click.

Another problem that I came across is properly showing and hiding the editors.  When I tried to use the built in options they would not show properly when toggling. I had problems with the textareas being set to visible.   To solve this problem I wrapped the original textarea inside a div and I show and hide the divs instead of the actual text area.

I like so many things about the TinyMCE editor but these problems were very frustrating and took up far too much of my time.

#TinyMCE: Validation with MVC

Today I am trying to figure out how to do validation with TinyMCE editors while using MVC’ s unobtrusive validation.  I did a google search and came up with a large number of results that all said the same thing.  I couldn’t get any of them to work.  While testing I found the following solution.  It isn’t perfect but is pretty close to what I need.

Here is the solution I came up with. I didn’t need to add any other additional code to the page.

      $('form button[type=submit]').not('.cancel').click(function () {
        var form = $('#FormName');
        var isValid = form.valid();
        var istinymceValid = $('#ContentField').valid();
        if (!isValid || !istinymceValid) {
          return false;
        }
        return true;
      });

Bootstrap3 Dialog

Bootstrap3dialog

One of the great things about programming in the world today is that so much of the basic functionality I need can be found somewhere on the Web, as long as you know the correct search string.

I spent a good chunk of time looking for a quick and easy way to use Bootstrap modals without having a ton of ugly code on each page that isn’t really necessary.  Especially for modals that are repeated throughout the software.

This time I was looking for a Bootstrap modal that could be easily used for Alert and Confirmation boxes.  I couldn’t find one out there, even though I knew it should exist, so I built my own.  Then I plugged in a different search string and found exactly what I needed.

Bootstrap3 Dialog (Git Hub)is a nice clean simple solution that meets all our needs.  The code is well laid out and I was able to make some minor modifications that met our custom needs.