fralbo
fralbo

Reputation: 2664

Cannot render a dynamically added textarea as TinyMCE 4.1.8

I have a form where I statically create a TinyMCE editor which works fine.

Now, I want to dynamically add a textarea which I want to render as a TinyMCE editor.

According to what I found on the net, I wrote the following code:

function add_new_agpoitext() {
    $("#agpoitextslist").append(
'<div class="row"> \
    <div class="col-md-8"> \
        <input type="hidden" name="agpoitexts[' + next_agpoitext + '][sequence]" value="' + next_agpoitext + '"/> \
        <div class="form-group textarea"> \
            <label class="control-label" for="agpoitexts-' + next_agpoitext + '-paragraph"><?=__("Paragraphe ");?>next_agpoitext + ":"</label> \
            <textarea name="agpoitexts[' + next_agpoitext + '][paragraph]" class="form-control" placeholder="Texte" rows="5" id="agpoitexts-' + next_agpoitext + '-paragraph"></textarea> \
        </div> \
    </div> \
</div>');

    next_agpoitext = next_agpoitext + 1;

    var textAreaID = "#agpoitexts-" + next_agpoitext + "-paragraph";

    $(textAreaID).ready(function(){
        tinyMCE.execCommand('mceAddEditor', true, textAreaID); 
    });

    return 1;
}

And the TinyMCe init function is the following one:

tinymce.init({
    selector: "textarea",
    ....
    setup : function(ed) {

        ...
    },
});

So when I call add_new_agpoitext(), tinymce.init() is called and I can see that the textarea id is the right one. But the textarea is not rendered as a TinyMCE editor.

What is missing in my code?

I saw this How to add tinymce 4.x dynamically to textarea?, and so I tried to add tinymce.init() function after my append() call but it doesn't change anything and as my original tinymce.setup() is called, I don't think that the problem is here.

Upvotes: 0

Views: 536

Answers (1)

Vic
Vic

Reputation: 12507

You are incrementing next_agpoitext too soon. You should increment it after using it to build the textAreaID variable.

Let's say next_agpoitext has a value of 3:

  1. You are creating a <textarea> with id="agpoitexts-3-paragraph".
  2. You increment next_agpoitext. So it now has a value of 4
  3. You use the incremented value to build the textAreaID variable, which is assigned the value #agpoitexts-4-paragraph
  4. You are trying to call the mceAddEditor TinyMCE command on a textarea that doesn't actually exist in the DOM.

Edit: Also, according to the jQuery docs, you are not using .ready() properly. The ready event only fires for the whole document, you cannot add a listener for it on regular DOM elements:

The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

In conclusion:

  1. Increment next_agpoitext after building the textAreaID variable
  2. Remove the .ready() call that wraps tinyMCE.execCommand

Upvotes: 1

Related Questions