[CKEditor] ckeditor character count problem
Question
Forge component by Matthias Preuter

i am saving the value of variable which is bound to input field in database. i have set a onChange action to that input field and set a validation inside it i.e. if character length >500 , So when i started typing their is difference in the length of variable bound to that input field and the count shown at the bottom end of editor. So what should i do to make the count synchronize.

i have set the config properties as follows:

SyntaxEditor Code Snippet

"toolbarGroups: [
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'paragraph', groups: [ 'list', 'bidi', 'paragraph' ] },
        '/',
        { name: 'styles', groups: [ 'styles' ] },
    ],

removeButtons: 'Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Anchor,Language,BidiRtl,BidiLtr,CreateDiv,Find,Replace,Cut,Copy,Paste,PasteText,PasteFromWord,Templates,Save,NewPage,Preview,Print,Source,SelectAll,Scayt,Subscript,Superscript,RemoveFormat,Flash,Table,HorizontalRule,Smiley,SpecialChar,PageBreak,Iframe,ShowBlocks',


extraPlugins: 'wordcount,notification',

resize_enabled : false,

removePlugins: 'elementspath',

wordcount: {
    // Whether or not you want to show the Paragraphs Count
    showParagraphs: true,

    // Whether or not you want to show the Word Count
    showWordCount: true,

    // Whether or not you want to show the Char Count
    showCharCount: true,

    // Whether or not you want to count Spaces as Chars
    countSpacesAsChars: true,

    // Whether or not to include Html chars in the Char Count
    countHTML: true,
    
    // Maximum allowed Word Count, -1 is default for unlimited
    maxWordCount: -1,

    // Maximum allowed Char Count, -1 is default for unlimited
    maxCharCount: 500,

   // Option to limit the characters in the Editor, for example 200 in this case.
   charLimit: 500,
}
"


please suggest me something so that i can synchronize the count.


count.png

Hi Lovish,


From what I can tell, ckeditor saves your input as html and not as literal text.

So, for example, if you add a phrase like "Today I published a new app" you should expect a total count of 27 characters. Because ckeditor saves the input as html, you need to account for the html tags.

If you check the source code you'll get something like this:

Here, I just wrote 200 chars divided by 3 words but as you can see the actual total is 221 (21 more chars for the html tags).


Hope this helps you understand the component's behaviour a little better,

Davide Résio


Can confirm what David has said. We went through exactly this same issue where our customers complained that the character count was wrong but it is just the HTML formatting characters. If you want to allow 500 characters of real text then you will probably need to add up to 1/3 more. Also note that for the same reason doing searches or sorting on CKEditor text from a database doesn't always work, for example if the first word is bolded then it actually looks like "<b>Word" which sorts differently to just "Word". Same as doing a search on "First Word" wont find something like "First <b>Word</b>" where Word is bolded

mvp_badge
MVP

Use the HtmlToText function out there in HTMLUtils I think, then count the letters in that to get a legit character count. Or use a regex (I guess... \w+ and then count the matches will do) (or count of spaces) to get word count if you prefer that.

J.Ja

Justin James wrote:

Use the HtmlToText function out there in HTMLUtils I think, then count the letters in that to get a legit character count. Or use a regex (I guess... \w+ and then count the matches will do) (or count of spaces) to get word count if you prefer that.

J.Ja

We tried that but it can give a bit of a lag with large or complex formatted text if you stripping html on each keypress


mvp_badge
MVP

John Williams wrote:

Justin James wrote:

Use the HtmlToText function out there in HTMLUtils I think, then count the letters in that to get a legit character count. Or use a regex (I guess... \w+ and then count the matches will do) (or count of spaces) to get word count if you prefer that.

J.Ja

We tried that but it can give a bit of a lag with large or complex formatted text if you stripping html on each keypress


Then do it in JavaScript. Shouldn't be too tough.

J.Ja


Still creates a lag on large text, small text is ok but the more text the bigger the lag. We just explained to the clients. Also if you set the limit to 500 characters for a reason (ie database field size) then you really need an accurate count anyway. Our average ckedit size was between 2000 and 4000 characters, 500 might be ok with the htmltotext.

I just reread the OP. have you tried setting the "countHTML: true," to false? I hadn't noticed that property there before myself. But if that works then remember your real character count will be higher so if your putting it into a database field with max 500 characters you could have a problem.

John Williams wrote:

I just reread the OP. have you tried setting the "countHTML: true," to false? I hadn't noticed that property there before myself. But if that works then remember your real character count will be higher so if your putting it into a database field with max 500 characters you could have a problem.

Good morning John,


Previously I had that property set to false and the behaviour was as I've described.

Setting the countHTML property to true the behaviour is as follows:


My count (on the left) tells that there are 55 characters present in that input but the char count from the actual component gives me a higher number.


Best regards,

Davide Résio

Hi, I had the same issue, the only way to have a more accurate count was to change some configurations on the editor.The plugin is returning a higher number because is counting newlines a other tabulations.

Add the code in red to CKeditor WB, this will remove tabulations and the count will start to match the number of characters.

I strongly advise you to remove the limit of number of characters on the associated input and add a server side validation to check if the number of characters is not higher that your attribute on the DataBase. This way you will avoid saving  bad html or even getting db errors while saving.


ckConfig.on = {
            saveSnapshot: $('#' + ssInputId)[0].ckEditorUpdate,
            key: $('#' + ssInputId)[0].ckEditorUpdate,
            afterCommandExec: $('#' + ssInputId)[0].ckEditorUpdate,
            change: $('#' + ssInputId)[0].ckEditorUpdate,
            instanceReady: function() {
                                // Output self-closing tags the HTML4 way, like <br>.
                                this.dataProcessor.writer.selfClosingEnd = '>';
                                this.dataProcessor.writer.lineBreakChars = '';

                                // Use line breaks for block elements, tables, and lists.
                                var dtd = CKEDITOR.dtd;
                                for ( var e in CKEDITOR.tools.extend( {}, dtd.$nonBodyContent, dtd.$block, dtd.$listItem, dtd.$tableContent ) ) {
                                    this.dataProcessor.writer.setRules( e, {
                                        indent: false,
                                        breakBeforeOpen: false,
                                        breakAfterOpen: false,
                                        breakBeforeClose: false,
                                        breakAfterClose: false
                                    });
                                }
                            }
        };

How can I change the idiom/language... to portuguese (BR)

Is better to create a new discussion this is already marked as solved, and your question is not related at all with this discussion.

Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.