Limit the number of character in tinyMCE

后端 未结 16 1044
心在旅途
心在旅途 2020-11-29 07:44

Im using tinyMCe for my project.Everything is working fine but now i want to restrict the number of character that will be insert into tinyMce text

相关标签:
16条回答
  • 2020-11-29 08:00
        // Returns text statistics for the specified editor by id
    function getStats(id) {
        var body = tinymce.get(id).getBody(), text = tinymce.trim(body.innerText || body.textContent);
    
        return {
            chars: text.length,
            words: text.split(/[\w\u2019\'-]+/).length
        };
    } 
    
    
    
    
    
    function submitForm() {
            // Check if the user has entered less than 10 characters
            if (getStats('content').chars < 10) {
                alert("You need to enter 1000 characters or more.");
                return;
            }
    
            // Check if the user has entered less than 1 words
            if (getStats('content').words < 1) {
                alert("You need to enter 1 words or more.");
                return;
            }
    
            // Submit the form
            document.forms[0].submit();
        }
    

    http://www.tinymce.com/wiki.php/How_to_limit_number_of_characters/words

    Hope it helps

    0 讨论(0)
  • 2020-11-29 08:00

    Ok with the new tinyMCE4X thing's change a little bit.

        tinymce.init({
        charLimit : 10, // this is a default value which can get modified later
        setup: function(editor) {
            editor.on('change', function(e) {
                //define local variables
                var tinymax, tinylen, htmlcount;
                //setting our max character limit
                tinymax = this.settings.charLimit;
                //grabbing the length of the curent editors content
                tinylen = this.getContent().length;
                if (tinylen > tinymax) {
                    alert('to big');
                }
            });
        }
        });
    
    0 讨论(0)
  • 2020-11-29 08:02

    the solution worked for me but with a small bug. If you see the character count is not right, thats because you use

    ed.on("KeyDown")
    

    change it to

    ed.on("KeyUp") 
    

    ,then it will work fine. I havent tested it with ('Change'). it may works too!

    0 讨论(0)
  • 2020-11-29 08:04

    easiest way:

    contentContentLenght = tinyMCE.activeEditor.getContent({format : 'text'}).length; //takes lenght of current editor
    
    if (contentContentLenght > 1499) {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    } // 1500 is my limit in mine project.
    

    to prevent paste:

    editor.on('paste', function(e){
                contentContentLenght = tinyMCE.activeEditor.getContent({format : 'text'}).length;
                var data = e.clipboardData.getData('Text');
                if (data.length > (1500 - contentContentLenght)) {
                    return false;
                } else {
                    return true;
                }
            });
    
    0 讨论(0)
  • 2020-11-29 08:06

    This works in tinyMCE 4.3.12 and also captures pasting:

    EDIT: Fixed bugs and extended code to display a character counter under the editor. Possibly not the best way as it relies a bit on the current HTML structure of tinyMCE having the editor div before the hidden textarea.

    This version only counts the text length and ignores HTML tag length. To count full HTML length, replace all "innerText" with "innerHTML".

    tinymce.init({
        max_chars: 1000, // max. allowed chars
        setup: function (ed) {
            var allowedKeys = [8, 37, 38, 39, 40, 46]; // backspace, delete and cursor keys
            ed.on('keydown', function (e) {
                if (allowedKeys.indexOf(e.keyCode) != -1) return true;
                if (tinymce_getContentLength() + 1 > this.settings.max_chars) {
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }
                return true;
            });
            ed.on('keyup', function (e) {
                tinymce_updateCharCounter(this, tinymce_getContentLength());
            });
        },
        init_instance_callback: function () { // initialize counter div
            $('#' + this.id).prev().append('<div class="char_count" style="text-align:right"></div>');
            tinymce_updateCharCounter(this, tinymce_getContentLength());
        },
        paste_preprocess: function (plugin, args) {
            var editor = tinymce.get(tinymce.activeEditor.id);
            var len = editor.contentDocument.body.innerText.length;
            var text = $(args.content).text();
            if (len + text.length > editor.settings.max_chars) {
                alert('Pasting this exceeds the maximum allowed number of ' + editor.settings.max_chars + ' characters.');
                args.content = '';
            } else {
                tinymce_updateCharCounter(editor, len + text.length);
            }
        }
    });
    
    function tinymce_updateCharCounter(el, len) {
        $('#' + el.id).prev().find('.char_count').text(len + '/' + el.settings.max_chars);
    }
    
    function tinymce_getContentLength() {
        return tinymce.get(tinymce.activeEditor.id).contentDocument.body.innerText.length;
    }
    

    Reference: How can I prevent tinyMCE's paste event?

    0 讨论(0)
  • 2020-11-29 08:07

    tinyMCE not provide any way to limit the character and restrict user to enter more character, the only way is use any explicit plugin or your logic for it. Below code show issue raised with me, it is working properly.

    This is used on textarea having id summary and one another paragrap id character_count that used to show character count. User is not able to enter more character than max limit, Inthis case only backspace key is working. You can free to use any key by giving ascii value if the key in condition.

    tinymce.init({
      selector: '#summary',  // change this value according to your HTML
      auto_focus: 'element1',
      statusbar: false,
      toolbar: 'undo redo | styleselect | bold italic underline | formatselect | aligncenter | fontselect',
      setup: function (ed) {
                ed.on('KeyDown', function (e) { 
                    var max = 150;
                    var count = CountCharacters();
                    if (count >= max) {
                            if(e.keyCode != 8 && e.keyCode != 46)
                              tinymce.dom.Event.cancel(e);
                              document.getElementById("character_count").innerHTML = "Maximun allowed character is: 150";
    
                    } else {
                        document.getElementById("character_count").innerHTML = "Characters: " + count;
                     }
                });
    
            }
     });
    
     function CountCharacters() {
        var body = tinymce.get("summary").getBody();
        var content = tinymce.trim(body.innerText || body.textContent);
        return content.length;
    };
    
    0 讨论(0)
提交回复
热议问题