Ограничить количество символов в tinyMCE - программирование

Ограничить количество символов в tinyMCE

Im использует tinyMCe для моего проекта. Все работает нормально, но теперь я хочу ограничить количество символов, которые будут вставляться в tinyMCe textarea

tinyMCE.init({
// General options
mode : "textareas",
theme : "simple",
plugins : "autolink,lists,pagebreak,style,table,save,advhr,advimage,advlink,emotions,media,noneditable,nonbreaking",

// Theme options
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect",
theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,code,|,forecolor,backcolor",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
max_chars : "10",
max_chars_indicator : "lengthBox",
theme_advanced_resizing : true
});

Я использовал: -

max_chars : "10",
max_chars_indicator : "lengthBox",

но все еще не работает. Спасибо заранее.

4b9b3361

Ответ 1

Это работает в tinyMCE 4.3.12, а также захватывает вставку:

EDIT: исправлены ошибки и расширенный код для отображения символьного счетчика в редакторе. Возможно, это не самый лучший способ, поскольку он немного полагается на текущую структуру HTML tinyMCE, имеющую редактор div перед скрытой текстовой областью.

Эта версия учитывает только длину текста и игнорирует длину тега HTML. Чтобы подсчитать полную длину HTML, замените все "innerText" на "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;
}

Ссылка: Как предотвратить событие вставки tinyMCE?

Ответ 2

TinyMCE 4+
+
JQuery

<textarea id="description_edit" name="description_edit"><?=htmlspecialchars($this->company->description);?></textarea>

<div><span>Characters left:</span> <span id="chars_left"></span></div>


<script type="text/javascript" src="/js/tinymce/tinymce.min.js"></script>
<script>
    var max_chars = 200; //max characters
    var max_for_html = 300; //max characters for html tags
    var allowed_keys = [8, 13, 16, 17, 18, 20, 33, 34, 35, 36, 37, 38, 39, 40, 46];
    var chars_without_html = 0;

    function alarmChars() {
        if (chars_without_html > (max_chars - 25)) {
            $('#chars_left').css('color', 'red');
        } else {
            $('#chars_left').css('color', 'gray');
        }
    }

    $(function () {
        tinymce.init({
            selector: "#description_edit",
            theme: "modern",
            width: 320,
            height: 130,
            plugins: [
                "advlist autolink lists charmap print preview hr anchor pagebreak",
                "searchreplace visualblocks visualchars code insertdatetime media nonbreaking",
                "save table contextmenu directionality paste textcolor"
            ],
            image_advtab: true,
            language: 'en',
            menubar: false,
            statusbar: false,

            setup: function (ed) {
                ed.on("KeyDown", function (ed, evt) {
                    chars_without_html = $.trim(tinyMCE.activeEditor.getContent().replace(/(<([^>]+)>)/ig, "")).length;
                    chars_with_html = tinyMCE.activeEditor.getContent().length;
                    var key = ed.keyCode;

                    $('#chars_left').html(max_chars - chars_without_html);

                    if (allowed_keys.indexOf(key) != -1) {
                        alarmChars();
                        return;
                    }

                    if (chars_with_html > (max_chars + max_for_html)) {
                        ed.stopPropagation();
                        ed.preventDefault();
                    } else if (chars_without_html > max_chars - 1 && key != 8 && key != 46) {
                        alert('Characters limit!');
                        ed.stopPropagation();
                        ed.preventDefault();
                    }
                    alarmChars();
                });
            },

            toolbar: "bold italic underline | alignleft aligncenter alignright alignjustify | forecolor backcolor | bullist numlist | charmap",
            style_formats: [
                {title: 'Bold text', inline: 'b'},
                {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
                {title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
                {title: 'Example 1', inline: 'span', classes: 'example1'},
                {title: 'Example 2', inline: 'span', classes: 'example2'},
                {title: 'Table styles'},
                {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
            ]
        });

        chars_without_html = $.trim($("#description_edit").text().replace(/(<([^>]+)>)/ig, "")).length;
        $('#chars_left').html(max_chars - chars_without_html);
        alarmChars();
    });
</script>

Ответ 3

Ответы выше были великолепны! Я сделал небольшую поправку, чтобы мы могли установить max_chars, добавив ее как атрибут самому элементу textarea

setup : function(ed) {
        ed.onKeyDown.add(function(ed, evt) {
            //if ( $(ed.getBody()).text().length+1 > ed.getParam('max_chars')){
            if ( $(ed.getBody()).text().length+1 > $(tinyMCE.get(tinyMCE.activeEditor.id).getElement()).attr('max_chars')){
                evt.preventDefault();
                evt.stopPropagation();
                return false;
            }
        });
    } 

Ответ 4

Предоставление поддержки для возврата и удаления ключей. Моя версия:

max_chars : 2000,
max_chars_indicator : ".maxCharsSpan",

setup : function(ed) {  
    wordcount = 0;
    wordCounter = function (ed, e) {
        text = ed.getContent().replace(/<[^>]*>/g, '').replace(/\s+/g, ' ');
        text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        this.wordcount = ed.getParam('max_chars') - text.length;
        $(ed.getParam('max_chars_indicator')).text( this.wordcount + " (out of " +ed.getParam('max_chars')+ ") char(s) left." );
    };

    ed.onKeyUp.add( wordCounter );

    ed.onKeyDown.add(function(ed, e) {
    if (this.wordcount <= 0 && e.keyCode != 8 && e.keyCode != 46) {
         tinymce.dom.Event.cancel(e);
    }
});

Ответ 5

    // 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

Надеюсь, что это поможет

Ответ 6

Нет настройки конфигурации tinymce max_chars, за исключением того, что вы ее реализуете самостоятельно:

tinyMCE.init({
   ...
   max_chars : "10",
   setup : function(ed) {
      ed.onKeyDown.add(function(ed, evt) {

        if ( $(ed.getBody()).text().length > ed.getParam('max_char')){
          e.preventDefault();
          e.stopPropagation();
          return false;
        } 

      });
   }
});

Ответ 7

Просто чтобы немного улучшить хороший пример, предоставленный Владимиром Мирошниченко, получить более точный счет, в основном для языков с акцентированными персонажами.

Я также использую Javascript SpellChecker, поскольку tinyMCE one (4.1) больше не может быть использован. Таким образом, ed.addButton() будет включать кнопку на панели инструментов, чтобы вызвать $Spelling.SpellCheckInWindow( "редакторы" ). Это отлично работает с tinyMCE 4.1.7.

Я также добавил количество слов, если вы предпочитаете запускать будильник вместо слова.

<textarea id="paragraph1" name="description_edit"><?=htmlspecialchars($this->company->description);?></textarea>

<div><span>Characters left:</span> <span id="chars_left"></span></div>

<script type="text/javascript" src="tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="JavaScriptSpellCheck/include.js"></script>

<script>
var max_chars    = 300; //max characters
var max_for_html = 1000; //max characters for html tags
var allowed_keys = [8, 13, 16, 17, 18, 20, 33, 34, 35,36, 37, 38, 39, 40, 46];
var chars_without_html = 0;

function alarmChars(){
    if(chars_without_html > (max_chars - 25)){
        $('#chars_left').css('color','red');
    }else{
        $('#chars_left').css('color','gray');
    }
}        

$(function() {
    tinymce.init({
        selector: "textarea#paragraph1",
        theme: "modern",
        plugins: [
            "advlist autolink lists charmap preview hr anchor pagebreak",
            "visualblocks visualchars insertdatetime nonbreaking",
            "directionality paste textcolor"
        ],
        menubar:false,
        statusbar:false,

        toolbar: "bold italic underline | alignleft aligncenter alignright alignjustify | forecolor backcolor | bullist numlist | charmap | preview | Spellcheck", 

        setup : function(ed) {
            ed.addButton('Spellcheck', {
                title : 'Spellcheck',
                image : '/img/dict.png',
                onclick : function() {
                    // Add you own code to execute something on click
                    $Spelling.SpellCheckInWindow('editors');
                }
            });

            ed.on("KeyDown", function(ed,evt) {
                    whtml = tinyMCE.activeEditor.getContent();

                    without_html = whtml.replace(/(<([^>]+)>)/ig,"");
                    without_html = without_html.replace(/&([A-za- z])(?:acute|cedil|caron|circ|grave|orn|ring|slash|th|tilde|uml);/ig,'$1');
                    without_html = without_html.replace(/&hellip;/ig,'...');
                    without_html = without_html.replace(/&rsquo;/ig,'\'');
                    without_html = $.trim(without_html.replace(/&([A-za-z]{2})(?:lig);/ig,'$1'));

                    chars_without_html = without_html.length;
                    chars_with_html    = whtml.length;

                    wordscount = without_html.split(/[ ]+/).length;  // Just to get the wordcount, in case...

                    var key = ed.keyCode;

                    $('#chars_left').html(max_chars - chars_without_html);

                    if(allowed_keys.indexOf(key) != -1){
                        alarmChars();
                        return;                                                         
                    }

                    if (chars_with_html > (max_chars + max_for_html)){
                        ed.stopPropagation();
                        ed.preventDefault();
                    }else if (chars_without_html > max_chars-1 && key != 8 && key != 46){
                        alert('Characters limit!');
                        ed.stopPropagation();
                        ed.preventDefault();
                    }
                    alarmChars();                                                   
                }
            );
        },
    });

    whtml = $("#paragraph1").text();

    without_html = whtml.replace(/(<([^>]+)>)/ig,"");
    without_html = without_html.replace(/&([A-za-z])(?:acute|cedil|caron|circ|grave|orn|ring|slash|th|tilde|uml);/ig,'$1');
    without_html = without_html.replace(/&hellip;/ig,'...');
    without_html = without_html.replace(/&rsquo;/ig,'\'');
    without_html = $.trim(without_html.replace(/&([A-za-z]{2})(?:lig);/ig,'$1'));

    chars_without_html = without_html.length;

    $('#chars_left').html(max_chars - chars_without_html);
    alarmChars();                                           
});    

Надеюсь, это поможет, поскольку команда tinyMCE, похоже, немного упряма на эту тему...

Ответ 8

решение работало для меня, но с небольшой ошибкой. Если вы видите, что количество символов неверно, это потому, что вы используете

ed.on("KeyDown")

измените его на

ed.on("KeyUp") 

тогда он будет работать нормально. Я не тестировал его ( "Изменить" ). он тоже может работать!

Ответ 9

Хорошо, что новая вещь tinyMCE4X немного изменилась.

    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');
            }
        });
    }
    });

Ответ 10

TinyMCE + AngularJS

Здесь вы можете ограничить максимальное количество символов на интерфейсе с помощью ng-maxlength директивы от AngularJS.

Параметр: ngMaxlength
Тип: номер
Детали: Устанавливает maxlength ключ проверки достоверности, если значение больше, чем maxlength.

Обратите внимание, что эта директива не просто считает отображаемые текстовые символы, она считает весь текст внутри <textarea> в HTML, как теги и скрипты.

Прежде всего, включите AngularJS, TinyMCE 4 дистрибутива и обертка AngularUI для TinyMCE.

HTML:

<form name="form" action="#">
    <textarea ng-model="myMCEContent" ui-tinymce ng-maxlength="200" name="body"></textarea>
    <span ng-show="form.body.$error.maxlength" class="error">Reached limit!/span>
</form>

JavaScript:

angular.module('myApp', ['ui.tinymce'])
.config(['$sceProvider', function($sceProvider) {
    // Disable Strict Contextual Escaping
    $sceProvider.enabled(false);
}])
.constant('uiTinymceConfig', {/*...*/})
.controller('myCtrl', ['$scope', function($scope) {
    // ...
}]);

jsFiddle

! Внимание!

Прочитайте руководство перед использованием этого решения, чтобы полностью понять последствия отключения SCE в AngularJS: $sce service.

Ответ 11

tinyMCE не предоставляет возможности ограничить символ и ограничивать пользователя вводить больше символов, единственный способ - использовать какой-либо явный плагин или вашу логику для него. Ниже приведен код, поднятый мной, он работает правильно.

Это используется для textarea с идентификатором summary и еще одним идентификатором paragrap character_count, который используется для отображения количества символов. Пользователь не может ввести больше символа, чем max limit, в этом случае работает только клавиша backspace. Вы можете свободно использовать любую клавишу, указав значение ascii, если ключ в состоянии.

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;
};

Ответ 12

Самый простой способ:

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.

чтобы предотвратить вставку:

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;
            }
        });

Ответ 13

Решение ниже работает хорошо для меня: 1 - в html-коде текстового поля необходимо указать значение maxlength и id текстовой области.
2 - в части скрипта, код ниже. Если хотите, раскомментируйте строку alert() и поместите свое сообщение.

<script type="text/javascript">
  tinymce.init ({
    ...
    ...
      setup: function(ed) {
        var maxlength = parseInt($("#" + (ed.id)).attr("maxlength"));
        var count = 0;
        ed.on("keydown", function(e) {
          count++;
          if (count > maxlength) {
            // alert("You have reached the character limit");
            e.stopPropagation();
            return false;
          }
        });
     },
<textarea type="text" id="test" name="test" maxlength="10"></textarea>

Ответ 14

Это решение, которое сработало для меня.

Я в основном взял код, предоставленный @needfulthing, и исправил ошибки и улучшил его.

function initTinymce(){

        tinymce.init({
            selector: '.richtext-editable',
            plugins: ['paste'],

            max_chars: 50000, // max. allowed chars

            setup: function (ed) {                              
                var allowedKeys = [8, 13, 16, 17, 18, 20, 33, 34, 35, 36, 37, 38, 39, 40, 46];
                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;                             
                if (len + args.content.length > editor.settings.max_chars) {
                    alert('Pasting this exceeds the maximum allowed number of ' + editor.settings.max_chars + ' characters for the input.');
                    args.content = '';
                }                                   
                tinymce_updateCharCounter(editor, len + args.content.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;
        }

}

Ответ 15

Ответы Thariama были удивительными, только что реализовали его, и это было именно то, что я искал, просто сделал несколько изменений:

    max_chars : "10",
    setup : function(ed) {
        ed.onKeyDown.add(function(ed, evt) {
            if ( $(ed.getBody()).text().length+1 > ed.getParam('max_chars')){
                evt.preventDefault();
                evt.stopPropagation();
                return false;
            }
        });
    } 

Спасибо, Тариама.