TinyMCE text editor max char limit

余生长醉 提交于 2019-12-03 05:58:27

I suggest you execute your code onKeyDown, because on KeyUp the letter is already in the editor.

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

I had the same issue and found this link very useful: http://www.ryann.ca/?p=186

Although I changed this slightly so that it reads the attribute of maxlength direct from the textarea.

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

Hope it will work :)

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;
                }
            });
        },
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!