setContent of an textarea with tinyMCE

Viewed 58078

I have some textareas and all of them are with tinyMCE.

I would like to set the content of the specific textarea, but I can't find how.

I have tryed this:

 tinyMCE.get('title').setContent(selected_article_title);

here is my textarea:

<textarea style="width: 95%;" name="Title"  id="title"></textarea>

And here my tinyMCE init:

tinyMCE.init({
// General options
mode : "specific_textareas",
theme : "advanced",
width: "100%",
plugins : "pagebreak,paste,fullscreen,visualchars",

// Theme options
theme_advanced_buttons1 : "code,|,bold,italic,underline,|,sub,sup,|,charmap,|,fullscreen,|,bullist,numlist,|,pasteword",
theme_advanced_buttons2 :"",
theme_advanced_buttons3 :"",
theme_advanced_buttons4 :"",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
valid_elements : "i,sub,sup",
invalid_elements : "p, script",
editor_deselector : "mceOthers"
});

I don't know why this is not working, I am using the exemple from the tinyMCE website http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.setContent

10 Answers

In TinyMCE 5, you can do this using the setContent() method.

Let’s say you have initialized the editor on a textarea with id=”myTextarea”. First access the editor using that same id, then call setContent(). For example:

tinymce.get('myTextarea').setContent('<p>Hello world!</p>');

Or, instead of accessing the editor by id, you can access the active editor:

tinymce.activeEditor.setContent('<p>Hello world!</p>');

More info and examples here: https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce.

The following works with tinymce version 4, and doesn't show the editor as a textarea while it's being dragged:

function initializeEditors() {
    var editorContent = {};
    $("#photo-list").sortable({
        start: function (e, ui) {
            $('.attachment-info').each(function () {
                var id = $(this).attr('id');
                editorContent[id] = tinyMCE.get(id).getContent();
            });
        },
        stop: function (e, ui) {
            $('.attachment-info').each(function () {
                var id = $(this).attr('id');
                tinymce.execCommand('mceRemoveEditor', false, id);
                tinymce.execCommand('mceAddEditor', true, id);
                tinyMCE.get(id).setContent(editorContent[id]);
            });
        }
    });
}

I just wrote this instead of setContent

const textarea = document.querySelector('#title')
textarea.innerHTML = selected_article_title

and it worked

I'm a bit late to the party, but since tinyMCE version 5 you should use:

tinymce.activeEditor.execCommand('mceInsertContent', false, 'My new content');
Related