Search code examples
javascriptjqueryckeditor

Adding CKEditor textareas dynamically


I'm creating an app where users can upload files and add a description and file title for each file.

I'm using jQuery to add more inputs dynamically, I wanted to add basic markup such as bold text, italic text, etc to the description and decided to use CKEditor.

The first textarea works properly and gets initiated as soon as a user opens the page.

However, the ones that I'm trying to add dynamically do not get initiated as a CKEditor textarea.

I tried this script, but it doesn't work. Any help is appreciated.

<script type="text/javascript">
$(document).ready(function() {
    var CKeditor = $(this).find('.dynamic-ckeditor-textarea')
    CKeditor.ckeditor()
});
</script>

This is the form I'm using.

<div class="row bg-custom">
  <div class="col-12">
    <form class="add-post-form form-signin widthfix" enctype="multipart/form-data" action="upload-handler.php?id=<?php echo $lastId; ?>" method="post">
      <ul id="fieldList">
        <li>
          <input class="form-control topborder" type='file' name='postFile[]'>
        </li>
        <li>
          <input class="form-control fixborder" type='text' name='postName[]' placeholder='File title / name'>
        </li>
        <li>
          <textarea class='form-control fixborder' id="image-desc-editor" name='postDesc[]' placeholder='File description'></textarea>
        </li>
      </ul>
      <button type="button" class="form-control" id="addMore" name="button">Another file</button>
      <br>
      <input type="submit" name=""  class="form-control" value="Upload files">
    </form>
  </div>
</div>

This is the jQuery I'm using to add more inputs:

$(function() {
  $("#addMore").click(function(e) {
    e.preventDefault();
    $("#fieldList").append("<li>&nbsp;</li>");
    $("#fieldList").append("<li><input type='file' class='form-control topborder' name='postFile[]'></li>");
    $("#fieldList").append("<li><input type='text' class='form-control fixborder' name='postName[]' placeholder='File title / name'></li>");
    $("#fieldList").append("<li><textarea id='image-desc-editor' class='form-control fixborder dynamic-ckeditor-textarea' name='postDesc[]' placeholder='File description'></textarea></li>");
  });
});

Solution

  • I think you can do it this way.

    $(document).ready(function() {
        CKEditorChange('image-desc-editor-0');
    });
    
    var i = 1;
    
    $(function() {
      $("#addMore").click(function(e) {
        e.preventDefault();
        $("#fieldList").append("<li>&nbsp;</li>");
        $("#fieldList").append("<li><input type='file' class='form-control topborder' name='postFile[]'></li>");
        $("#fieldList").append("<li><input type='text' class='form-control fixborder' name='postName[]' placeholder='File title / name'></li>");
        $("#fieldList").append("<li><textarea id='image-desc-editor-"+i+"' class='form-control fixborder dynamic-ckeditor-textarea' name='postDesc[]' placeholder='File description'></textarea></li>");
        CKEditorChange('image-desc-editor-' + $(this).attr('rel'));
        $(this).attr('rel', parseInt($(this).attr('rel')) + parseInt(1));
        i++;
      });
    });
    
    function CKEditorChange(name) {
    
      CKEDITOR.replace(name, {
        toolbar: [{
            name: 'document',
            items: ['Print']
          },
          {
            name: 'clipboard',
            items: ['Undo', 'Redo']
          },
          {
            name: 'styles',
            items: ['Format', 'Font', 'FontSize']
          },
          {
            name: 'basicstyles',
            items: ['Bold', 'Italic', 'Underline', 'Strike', 'RemoveFormat', 'CopyFormatting']
          },
          {
            name: 'colors',
            items: ['TextColor', 'BGColor']
          },
          {
            name: 'align',
            items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']
          },
          {
            name: 'links',
            items: ['Link', 'Unlink']
          },
          {
            name: 'paragraph',
            items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote']
          },
          {
            name: 'insert',
            items: ['Image', 'Table']
          },
          {
            name: 'tools',
            items: ['Maximize']
          },
          {
            name: 'editing',
            items: ['Scayt']
          }
        ],
        filebrowserUploadUrl: 'request.php?pID=Upload',
        customConfig: '',
        disallowedContent: 'img{width,height,float}',
        extraAllowedContent: 'img[width,height,align]',
        extraPlugins: 'tableresize,uploadimage,uploadfile',
        height: 800,
        contentsCss: ['https://cdn.ckeditor.com/4.8.0/full-all/contents.css'],
        bodyClass: 'document-editor',
        format_tags: 'p;h1;h2;h3;pre',
        removeDialogTabs: 'image:advanced;link:advanced',
        stylesSet: [{
            name: 'Marker',
            element: 'span',
            attributes: {
              'class': 'marker'
            }
          },
          {
            name: 'Cited Work',
            element: 'cite'
          },
          {
            name: 'Inline Quotation',
            element: 'q'
          },
          {
            name: 'Special Container',
            element: 'div',
            styles: {
              padding: '5px 10px',
              background: '#eee',
              border: '1px solid #ccc'
            }
          },
          {
            name: 'Compact table',
            element: 'table',
            attributes: {
              cellpadding: '5',
              cellspacing: '0',
              border: '1',
              bordercolor: '#ccc'
            },
            styles: {
              'border-collapse': 'collapse'
            }
          },
          {
            name: 'Borderless Table',
            element: 'table',
            styles: {
              'border-style': 'hidden',
              'background-color': '#E6E6FA'
            }
          },
          {
            name: 'Square Bulleted List',
            element: 'ul',
            styles: {
              'list-style-type': 'square'
            }
          }
        ]
      });
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.ckeditor.com/4.8.0/full-all/ckeditor.js"></script>
    
    <div class="row bg-custom">
      <div class="col-12">
        <form class="add-post-form form-signin widthfix" enctype="multipart/form-data" action="upload-handler.php?id=<?php echo $lastId; ?>" method="post">
          <ul id="fieldList">
            <li>
              <input class="form-control topborder" type='file' name='postFile[]'>
            </li>
            <li>
              <input class="form-control fixborder" type='text' name='postName[]' placeholder='File title / name'>
            </li>
            <li>
              <textarea class='form-control fixborder' id="image-desc-editor-0" name='postDesc[]' placeholder='File description'></textarea>
            </li>
          </ul>
          <button type="button" class="form-control" id="addMore" rel="1" name="button">Another file</button>
          <br>
          <input type="submit" name="" class="form-control" value="Upload files">
        </form>
      </div>
    </div>

    Update : This is the simplest use.

    function CKEditorChange(name) {
       CKEDITOR.replace(name);
    }