Как я могу добавить редактор TinyMCE в динамически добавляемую

#javascript #tinymce

#javascript #tinymce

Вопрос:

Как я могу добавить редактор TinyMCE ко всем <textarea> , которые были добавлены с помощью Javascript?

Вот мой код:

 function addFields() {
  var number = document.getElementById("no_of_description").value;
  var row = document.getElementById("clone-row");
  // $("#clone-row").empty()

  while (row.hasChildNodes()) {
    row.removeChild(row.lastChild);
  }
  for (i = 1; i <= number; i  ) {
    var column = document.createElement("div");
    column.setAttribute("class", "col-6 clone-column")
    row.appendChild(column);

    var label_title = document.createElement("label");
    label_title.setAttribute("for", "title_"   i)
    label_title.innerHTML = "Title "   i

    var input_title = document.createElement("input");
    input_title.setAttribute("class", "form-control");
    input_title.setAttribute("type", "text");
    input_title.setAttribute("id", "title_"   i);
    input_title.setAttribute("name", "title_"   i);
    input_title.setAttribute("placeholder", "Title"   i);


    column.appendChild(label_title);
    column.appendChild(input_title);
    column.appendChild(document.createElement("br"));

    var label_description = document.createElement("label");
    label_description.setAttribute("for", "description_"   i)
    label_description.innerHTML = "Description "   i

    var textarea = document.createElement("textarea");
    textarea.setAttribute("class", "form-control custom_TinyMCE");
    textarea.setAttribute("id", "description_"   i);
    textarea.setAttribute("name", "description_"   i);
    textarea.setAttribute("rows", 8);
    textarea.setAttribute("cols", 80);

    column.appendChild(label_description);
    column.appendChild(textarea);
    column.appendChild(document.createElement("br"));
    
    // tinymce.init({selector:'.custom_TinyMCE'});
    // This work only for last added <textarea>

  }
}  
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP VmmDGMN5t9UJ0Z" crossorigin="anonymous">

<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: '.custom_TinyMCE'
  });
</script>

<div class="container">
  <div class="form-row">
    <div class="col form-group">
      <label for="no_of_description">No. of description</label>
      <input type="number" class="form-control" id="no_of_description" name="no_of_description" value="0" min="0" onchange="addFields()">
    </div>
  </div>

  <div class="form-row" id="clone-row"></div>
</div>  

Ответ №1:

Есть два способа init создания экземпляра TinyMCE в вашем примере.

Вы можете использовать target: textarea или selector: "textarea#description_" i в init функции.

Смотрите https://fiddle.tiny.cloud/Buhaab для рабочей демо-версии.