Search code examples
jqueryasp.net-mvcckeditor

Limit/Count Characters in CKEditor w/ Jquery


I am using CKEditor for my wysiwyg editor and I need to monitor and limit the character count as they are typing I have a jquery script that works fine for a normal TextArea

<script type ="text/javascript" language="javascript">
    function limitChars(textid, limit, infodiv) {
        var text = $('.' + textid).val();
        var textlength = text.length;
        if (textlength > limit) {
            $('#' + infodiv).html('You cannot write more then ' + limit + ' characters!');
            $('#' + textid).val(text.substr(0, limit));
            return false;
        }
        else {
            $('#' + infodiv).html('You have ' + (limit - textlength) + ' characters left.');
            return true;
        }
    }

    $(function() {

        $('.comment-1').keyup(function() {
            limitChars('comment-1', 1000, 'charlimitinfo-1');
        })
    });

</script>

However this doesn't seem to work for when the textArea is replaced with the CKEditor any ideas?


Solution

  • 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.