Search code examples
javascriptjqueryhtmlstringtinymce-3

Character Limit is showing remaining characters in "negative" numbers


I am using tinyMCE version 3, I am using rich-text editor which counts the characters remaining on fly when giving the input. Since maxLength attribute does not work for tinyMCE3. I have hardcoded this way but its counting the blank charcters as well

< script type = "text/javascript" >

  tinyMCE.init({
    mode: "textareas",
    theme: "advanced",
    editor_selector: "mceEditor",
    theme_advanced_statusbar_location: "bottom",
    theme_advanced_path: false,
    statusbar: true,
    setup: function(editor) {
      editor.onKeyUp.add(function(c) {
        //    var maxCount = document.getElementById(editor.id).maxLength;
        var maxCount = 10;
        console.log(editor.id);
        var txt = $(editor.getBody()).text();
        var txtLen = txt.length;
        var value = maxCount - (txtLen);
        $(tinyMCE.activeEditor.getContainer()).find("#" + editor.id + "_path_row").html("Remaining chars: " + (value));

        if (txtLen > maxCount) {
          editor.setContent("");
          tinyMCE.activeEditor.selection.setContent(txt.substring(0, maxCount));
          tinyMCE.activeEditor.focus();
        }
      });
    }

  }); <
/script>
<textarea id="1" class="mceEditor" cols="100" rows="7" wrap="" maxlength="10">test sample</textarea>

Counting in negative

Counting in negative numbers and setting content to blank

and when I enter 2 characters in between Its removing the last two charcters is there any way I can stop giving the input after it reaches counter "0".


Solution

  • I'm not sure I understand your issue fully, as there are multiple things going on here.

    Showing remaining characters as negative

    I see that, with your code, if you type 11 characters, the 11th character will be deleted, but then remaining characters shows "-1" instead of "0". Is this your complaint? The reason why this is happening is because you trim the text content of the editor down to maxCount, but your remaining chars value was calculated before the trim occurs, so it still has the value of maxCount - untrimmed length. You could easily remedy this in multiple ways, including changing this:

    $(tinyMCE.activeEditor.getContainer()).find("#" + editor.id + "_path_row").html("Remaining chars: " + (value));
    

    to this:

    $(tinyMCE.activeEditor.getContainer()).find("#" + editor.id + "_path_row").html("Remaining chars: " + (value > 0 ? value : 0));
    

    Counting Blank Characters

    If you don't want any blank characters included in the count, use this:

    var txtLen = txt.replace(/\s/g,"").length;
    

    If you want to trim just the blank characters off the ends, use this:

    var txtLen = txt.trim().length;