How to add a character counter to AjaxControlToolkit HTMLEditorExtender control

Introduction:

How to add a character counter to AjaxControlToolkit HTMLEditorExtender control

Description:

In this article we are discussing how to add a line counter to HTML Editor Extender control. Usually it’s very straight forward to add character counter to textbox or textarea by using its id.We generally use keypress event in textbox control to call character counter function.

However when we use at HTMLEditorExtender control we will face an issue as the HTMLEditorExtender control will render as a div with ContentEditable property set to true.  Div doesn’t not have a keypress event.

gxjynaa

As a solution you can use Jquery bind method to attach DOMSubTreeModified event to div and then call the character counter function in this event.

Code to attach character counter:

<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
      $(document).ready(function () {
         //attach change event to div using Jquery css class selector
         $('.ajax__html_editor_extender_texteditor').bind("DOMSubtreeModified", function () {
         //call function to calcualate count on change event of div
             textCounter();
          });
     });
     function textCounter() {
          //Get the text count
          var divlength = $('.ajax__html_editor_extender_texteditor').text().length;
          //check if count greater than 100
          if (divlength &gt; 50) {
          //Trim the text
          var trimmedtext = $('.ajax__html_editor_extender_texteditor').text().substring(0, 100);
         //assign it to editor
         $('.ajax__html_editor_extender_texteditor').html(trimmedtext);
        } else{
            //reduce the allowed no of characters in textbox
            $('#remLen').val(50 - divlength);
        }
     }
</script>
Demo

TxtCounter

Advertisements

, , , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: