Подтвердить что ты не робот

Текстовый редактор TinyMCE max char limit

Я использую TinyMCE для <textarea>. Мое требование - ограничить размер символа до 2000, а также показывать оставшиеся символы где-то ниже панели инструментов. Мне как-то удалось получить номер персонажа; теперь я застреваю с отображением оставшихся символов и не допуская превышения лимита.

Вот мой код TinyMCE

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

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,
                               justifyleft,justifycenter,justifyright,
                               justifyfull,|,styleselect,formatselect,
                               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",
    theme_advanced_resizing : true,
    charLimit : 10, // this is a default value which can get modified later
    setup : function(ed) {
        //peform this action every time a key is pressed
        ed.onKeyUp.add(function(ed, e) {
        //define local variables
        var tinymax, tinylen, htmlcount;
        //manually setting our max character limit
        tinymax = ed.settings.charLimit;
        //grabbing the length of the curent editors content
        tinylen = ed.getContent().replace(/(<([^>]+)>)/ig,"").length;
        //setting up the text string that will display in the path area
        htmlcount = "HTML Character Count: " + tinylen + "/" + tinymax;
        //if the user has exceeded the max turn the path bar red.
        if (tinylen>tinymax){


        } 
        });
    }
});

Для целей тестирования я пытаюсь ограничить до 10 char.
Любые предложения приветствуются.

4b9b3361

Ответ 1

Я предлагаю вам выполнить свой код onKeyDown, потому что на KeyUp письмо уже находится в редакторе.

    //peform this action every time a key is pressed
    ed.onKeyDown.add(function(ed, e) {

      //define local variables
      var tinymax, tinylen, htmlcount;

      //manually setting our max character limit
      tinymax = ed.settings.charLimit;

      //grabbing the length of the curent editors content
      tinylen = ed.getContent().replace(/(<([^>]+)>)/ig,"").length;

      //setting up the text string that will display in the path area
      htmlcount = "HTML Character Count: " + tinylen + "/" + tinymax;

      //if the user has exceeded the max turn the path bar red.
      if (tinylen > tinymax){

        // place text string in path bar
        if ( $('#max_char_string').size() ){
          $('#max_char_string').html( '&nbsp;' + htmlcount);
        }
        else {
          $("div#"+ed.id+"_path_row").append('<span id="max_char_string">&nbsp;'+htmlcount+'</span>')
        }

        // prevent insertion of typed character
        e.preventDefault();
        e.stopPropagation();
        return false;
      } 

Ответ 2

У меня была такая же проблема, и я нашел эту ссылку очень полезной: http://www.ryann.ca/?p=186

Хотя я немного изменил это, чтобы он читал атрибут maxlength прямо из текстового поля.

tinyMCE.init({
    // Options
    setup : function(ed) {
        ed.onKeyUp.add(function(ed, e) {
            var tinylen, htmlcount, maxlength = $("#" + tinyMCE.activeEditor.id).attr("maxlength");
            if (maxlength) {
                // grabbing the length of the curent editors content
                tinylen = ed.getContent().length;

                htmlcount = "HTML Character Count: " + tinylen + "/" + maxlength;
                if (tinylen > maxlength) {
                    htmlcount = "<span style='font-weight:bold; color: #f00;'>" + htmlcount + "</span>";
                }

                // write the html count into the path row of the active editor
                tinymce.DOM.setHTML(tinymce.DOM.get(tinyMCE.activeEditor.id+ '_path_row'), htmlcount);
            }
        });//ed.onKeyUp.add
    }//setup
});

Ответ 3

Надеюсь, что это сработает:)

setup: function(ed) {            
            var maxlength = parseInt($('#'+(ed.id)).attr("maxlength"));
            var count = 0;
            ed.on('keydown', function(e) {
                count++;
                if (count >= maxlength)
                {
                    alert("false");
                    return false;
                }
            });
        },