Limit/Count Characters in CKEditor w/ Jquery

You can't grab the content of ckeditor so easily, for example with jquery and $("iframe").contents()... cause the ckeditor is not ready when your code fires. So you need to bind some functions on events when the instance of the editor is ready. After that, strip out the tags, trim the whitespaces from the beginning and the end and the counting can begin :)

    <input type="text" name="count" id="count" />
    <textarea id="ck"></textarea>
    <script type="text/javascript">
    $(document).ready(function()
    {
        var editor = CKEDITOR.replace('ck');
        editor.on("instanceReady", function(){
            this.document.on("keyup", ck_jq);
            this.document.on("paste", ck_jq);
        });

    });

    function ck_jq()
    {
        var len = CKEDITOR.instances['ck'].getData().replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '').replace(/^\s+|\s+$/g, '');
        $("#count").val(len.length);
    }

    </script>

HTH :)


If you can get the contents of the CKEditor as some other posts describe I have an idea about how to get the count of the characters entered. Once you have the contents, say

<b><span class="redText">H</span>ello <span>World!</span></b>

you can set that to the innerHTML of a hidden div, and then get the count of characters in the innerText of that div.

var elem = document.getElementById('hiddenTestDiv');
elem.innerHTML = '<b><span class="redText">H</span>ello <span>World!</span></b>';
var innerText = elem.innerText;  // equals 'Hello World!'
var contentLength = elem.innerText.length; // equals 12

I'd say it's not a perfect solution (for example just <hr> in your content will return 0 for length of innerText), but it may be close enough to work for you. It's kind of a strange situation counting the length of content of html, as Pekka said things like the length of a <hr> tag are open to interpretation.


The textarea is only a fallback element, and not updated live with the entered content. You would have to grab the contents of your CKEditor instance. This is definitely possible.

Check out the approaches in this question. that access CKEditor's contents on every content change.

I see a bigger problem for you, though. How many characters does this code have?:

<b><span class="redText">H</span>ello <span>World!</span></b>

(the answer - I think - is twelve)

or this:

<b>  <p style="font-size: 30px; font-weight: bold"></p>  </b>

(the answer - I think - is two spaces)

or this:

<hr>

(the answer - I think - is one, but that's down to interpretation really)

these are all conceivable strings that occur while writing and deleting text in CKEditor.

Assuming you want to count all characters without HTML tags, ignoring additional elements like images or horizontal lines, there is a strip_tags() function for JavaScript that you can use to strip down the data.