Search code examples
javascriptjqueryckeditormultiple-instances

How can I set multiple ckeditors of same class even if we add new ckeditor by appending on click a button?


I am planning to use multiple ckeditors on a single page. I need to append ckeditor on click a button but it's not working on the appended ckeditor. I have tried to insert the same class and call all ckeditors like "querySelectorAll('.editor')"

It's working properly on every '.editor' class. But my problem is with the ckeditor appended after clicking a button.

I found the '.editor' class has added by inspecting the source code. I think It will work, Now I need help.

    <div class="editors">
        <div class="editor">
          <p>Editor 1 here</p>
        </div>
        <div class="editor">
          <p>Editor 2 here</p>
        </div>
        </div>

        <button class="add-editor">Add New Editor</button>


        <script>
        $('.add-editor').click(function(){
         $('.editors').append(' <div class="editor"><p>Editor 3 here (Editor Not Loading here)</p></div>')
         });

 var allEditors = document.querySelectorAll('.editor');
  for (var i = 0; i < allEditors.length; ++i) {
    InlineEditor.create(allEditors[i]);
  }

        </script>

Solution

  • The trick here is that you only want to enable CKEditor to new editors. If you do it to existing ones, you'll get errors. You could solve that by adding an .enabled class to them, and that way, when you add a new one, you won't affect old ones.

    // Once on page load, for existing editors
    $(document).ready(enableEditors);
    // When you click on the button
    $('.add-editor').click(function() {
      var count = $('.editor').length + 1;
      $('.editors').append('<div class="editor"><p>Editor ' + count  + ' here</p></div>');
      enableEditors();
    });
    
    function enableEditors() {
      $('.editor:not(.enabled)').ckeditor().addClass('.enabled');
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.ckeditor.com/4.11.1/standard/ckeditor.js"></script>
    <script src="https://cdn.ckeditor.com/4.11.1/standard/adapters/jquery.js"></script>
    
    <div class="editors">
      <div class="editor">
        <p>Editor 1 here</p>
      </div>
      <div class="editor">
        <p>Editor 2 here</p>
      </div>
    </div>
    
    <button class="add-editor">Add New Editor</button>