5

I am using TinyMCE on a textarea in my page. I am trying to get the character and word count and the textarea is typed into. I have been trying various versions to make it work correctly, but without success. Here's the latest buggy version:

$().ready(function() {
    $('textarea.tinymce').tinymce({
        // Location of TinyMCE script
        script_url: 'jscripts/tiny_mce/tiny_mce.js',

        // General options
        theme: "advanced",
        plugins: "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

        // Theme options
        theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true,

        // Example content CSS (should be your site CSS)
        content_css: "css/content.css",

        // Drop lists for link/image/media/template dialogs
        template_external_list_url: "lists/template_list.js",
        external_link_list_url: "lists/link_list.js",
        external_image_list_url: "lists/image_list.js",
        media_external_list_url: "lists/media_list.js",

        // Replace values for the template plugin
        template_replace_values: {
            username: "Some User",
            staffid: "991234"
        },

        //setup:'tmceWordcount'
        setup: function(ed) {

            ed.onKeyUp.add(function(ed, e) {

                //Following does not work correctly
                //var strip = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/ig,"");

                //Neither does the code below
                var strip = (tinyMCE.activeEditor.getContent()).replace(/<[^>]+>/g, "");


                var text = strip.split(' ').length + " Words, " + strip.length + " Characters"
                tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id + '_path_row'), text);
            });
        }

    });
});

Here is my example. I am entering first word as: Me When I type the first word, it shows characters and word correctly. But as soon as I hit space to enter the next word, it shows the characters are 8. How? IMO, its including the HTML tags as well. The HTML code is as follows for the above entered text:

<p>Me&nbsp;</p>

I expect output to be 1 Word and 3 Characters (2 characters + 1 space). But its showing me 5 more characters. How is this happening & how can I stop it? If you do enter the next word, as soon as you start typing, it shows correct character count. But when you hit space again, it's adding more characters. So this problem seems to be occurring whenever space & enter buttons are hit. How can this be fixed?

Devner
  • 6,825
  • 11
  • 63
  • 104

4 Answers4

1

If you want to do something like this, then must add a jQuery function like so: http://jsfiddle.net/uA9Jx/

jQuery.fn.stripTags = function() {
        return this.replaceWith( this.text().replace(/<\/?[^>]+>/gi, '') );
};

Suppose this is your HTML:

<textarea id='bar'>This is <b>bold</b> and this is <i>italic</i>.</textarea>

And then you do:

$("#bar").stripTags();

Which will result in:

This is bold and this is italic.

Or this code works similarly: http://jsfiddle.net/cwbMX/

$("#bar").html( $("#bar").text().replace(/<\/?[^>]+>/gi, '') );
darkAsPitch
  • 1,855
  • 4
  • 23
  • 35
  • Hi, thanks for the code. I tried both the codes listed above and the same issue persists. For some weird reason, it is not removing the HTML tags. It is considering them. It should have taken the text as it is entered but instead, it is considering the HTML source. I even applied it twice, but still with the same effect. If you try this code, you will see that its alerting the HTML output even after I have applied replace function: `var strip = (tinyMCE.activeEditor.getContent()).replace(/<\/?[^>]+>/gi, ''); alert(strip.replace(/<\/?[^>]+>/gi, ''));` Any ideas on how to fix this? – Devner Jul 06 '12 at 18:55
0

You don't have to implement own solution, there is already a plugin which does both characters and word count: http://adamscheller.com/tinymce-count-characters-plugin/

Perry
  • 1
  • The link for this site no longer works, I think this is the new link: https://github.com/ncgordan/charwordcount – Navigatron Oct 28 '21 at 09:05
0

internet's memory is endless, and most of the threads on tinymce don't work in version 4 My solution is simple: change the wordcount plugin as follows: }return e + ' Chars: '+a.getContent().length} and change the onkeyup code by eliminating the check for keycode 32 a.on("keyup",function(a){b()})},0)}), works like a charm inserting these results into the tinymce instance needs a plugin indeed, but that is a minor modification of the example plugin

0

Just a few tips for those who want to work with several instances of tineMCE.

...    
setup: function(e){
        //I think in this case 'change' is better than 'keyup' because the user can click a button and change the code without typing.
        e.on('change', function(e){
                var len = tinymce.activeEditor.getContent().length; //Here we get the length of the content with the html tags.
                        var inputName       = tinymce.activeEditor.id; //here we get the name of the input or textarea.

                        var obj = $('input[name="'+inputName+'"]').parent();//Here we set a jquery object reference.

                        var maxLen = 400;
                        obj.find('.char-count').html(len); //Here we set a span tag with the length.

                        if(len > maxLen){
                            obj.find('.char-count').css('color','#fa8072'); //If the len is bigger than maxLen.
                        }else{
                            obj.find('.char-count').css('color','#808080'); //If the len is lower than maxLen.
                        }
                    });
                }
Joel
  • 315
  • 1
  • 10