6

I know there are so many solutions out there but cannot get right solution. I have written code for customized counter in tinyMCE version 3 which has maxlength attribute which is not working. I want to stop giving more text when counter reaches to 0, I have used setcontent("") and substring(0,maxcount) this seems to be problem because when I give any 2 characters in between its trimming last two charcters which should not be this way. Also I have tried using evt.preventDefault() Its preventing but unable to type IN again for keydown and keypress also excluded bacspace and delete but its not working right. here is my code.

    tinyMCE.init({
        mode: "textareas",
        theme: "advanced",
        editor_selector: "mceEditor",
        paste_auto_cleanup_on_paste: 'true',
        theme_advanced_disable: 'justifyleft,justifyright,justifyfull,justifycenter,indent,image,anchor,sub,sup,unlink,outdent,help,removeformat,link,fontselect,hr,styleselect,formatselect,charmap,separator,code,visualaid,strikethrough,fullscreen',
        theme_advanced_buttons1: 'bold,italic,underline,numlist,bullist,undo,redo,cleanup,spellchecker',
        theme_advanced_buttons2: "",
        theme_advanced_buttons3: "",
        plugins: 'spellchecker,fullscreen,paste',
        spellchecker_languages: '+English=en-us',
        spellchecker_rpc_url: '<%out.print(request.getContextPath());%>/jazzy-spellchecker',
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_path : false,
        statusbar: true,
        setup: function(editor)
        {
             editor.onKeyUp.add(function(evt)
            {
                var maxLengthRichTextArea = 5;
                 var inputRichTextArea = $(editor.getBody()).text();
                 var inputRichTextAreaLength = inputRichTextArea.length;
                 var value = maxLengthRichTextArea-inputRichTextAreaLength;
                 if(value >= 0)
                 {  
                 $(tinyMCE.activeEditor.getContainer()).find("#"+editor.id+"_path_row").html("Remaining chars: "+(value));
                }           
                if(inputRichTextAreaLength > maxLengthRichTextArea) {
                 editor.setContent("");
                tinyMCE.activeEditor.selection.setContent(inputRichTextArea.substring(0, maxLengthRichTextArea));
                }                  
            });
        }
    });

</script>

HTML

<textarea id="450225" class="mceEditor"  maxlength="10" style="display: none;"></textarea>

This is working good

But here when I add 6 its triimming of last digit 5

How to solve this issue and max count is actually a higher number which comes from database.

Juke
  • 1,306
  • 2
  • 11
  • 27
  • The TinyMCE doc shows [how to achieve that](https://www.tiny.cloud/docs-3x/howto/words/). – Ugo T. May 10 '19 at 18:31
  • Try `.preventDefault()` with `onKeyDown` event. – Louys Patrice Bessette May 10 '19 at 18:33
  • @UgoT. I dont want alert and the solution which is in the link was already implemented in the code. I said maxlength validation in html is not working. – Juke May 10 '19 at 18:46
  • @Juke No it is not already implemented in the code. It is an example of how using tinyMCE to get the current count of letters typed. It is up to you to do something with it, like preventing keypress on the textarea element when the counter >= limit. – Ugo T. May 10 '19 at 19:34
  • @LouysPatriceBessette have used this code if(inputRichTextAreaLength > maxLengthRichTextArea){ console.log("hello"); $(editor.getBody()).keydown(function(e) { console.log(editor.id); e.preventDefault(); //e.stopPropagation(); //return false }); Its working but its not letting me to edit or go back – Juke May 10 '19 at 19:36
  • @UgoT. I have used keydown but how to make it go back and edit – Juke May 10 '19 at 19:37
  • Exclude the 'delete' and 'backspace' keys from your condition to allow the user to remove some letters. – Ugo T. May 10 '19 at 19:39
  • @UgoT. can Exclude back ,front,top and bottom arrow as well? – Juke May 10 '19 at 19:45
  • Yes, this is a tool that gives you key codes : https://keycode.info/ – Ugo T. May 10 '19 at 19:48
  • I am using default prevented but its not preventing it. if((inputRichTextAreaLength+1) > maxLengthRichTextArea){ $(editor.getBody()).keydown(function(e) { e.preventDefault(); if(event.which == 8) { e.defaultPrevented return true; } }); } – Juke May 10 '19 at 20:22

1 Answers1

7

Here is a working example of what you are trying to achieve :

HTML :

<textarea id="text"></textarea>

Javascript :

tinymce.init({
  selector: "textarea#text",
  height: 500,
  menubar: false,
  setup: function(editor) {
    var maxlength = 5;
    var allowedKeys = [8, 37, 38, 39, 40];
    editor.on("keydown", function(e) {
      var count = $(editor.getBody()).text().length;
      if(allowedKeys.indexOf(e.which) != -1) {
         return;
      }
      if (count >= maxlength) {
        e.stopPropagation();
        return false;
      }
    });
  }
});

And the codepen, I hope that will help you ! In my code the max length is 5, but you can change it via the var maxlength.

Ugo T.
  • 1,068
  • 8
  • 12
  • In codepen when it reaches 5 and when I move the backarrow key to enter something its not allowing me to do – Juke May 13 '19 at 01:29
  • when I enter 3 characters and move backarrow for two spaces and enter something its taking only 1 charcater and is not letting me to enter more – Juke May 13 '19 at 01:50
  • and one more thing I am using is inputRichTextAreaLength I am getting confused with your count variable.. is that value in my code? – Juke May 13 '19 at 01:59
  • copy paste is not validating any counter its pasting complete content without checking – Juke May 13 '19 at 02:06
  • You must adapt this code to your needs. I've edited my answer to make it clearer and handle the arrow keys things to help you but for the `copy and paste` thing (that was not in your original question) you have to find out by yourself ([here](https://stackoverflow.com/questions/3387964/limit-paste-in-tinymce) for example). – Ugo T. May 13 '19 at 02:28
  • I have made lot many changes in my code but the latest code which you have shown is not allowing me to write text after backspace.. but n your code pen it does. the paste function I was talking about was when I have types 4 char and wanted to paste 130 chars, Its pasting everything irrespective of counter and keydown.. Or in the first place is there I can handle using some string methods. – Juke May 13 '19 at 02:59