Search code examples
javascripthtmltextareackeditor5

Set CKeditor data in the textarea with javascript


I have problem to set data in the ckeditor textarea. For example I need to set data <p><strong>Tilte</strong></p><p><i>123</i></p> in the textarea when I've clicked the save button, then the data will show in the textarea.

Below is I want the expected result:

output

Below is my coding that I've tried, I've used this method CKEDITOR.instances[agenda_mesyuarat].setData(testing); but it cannot work.

let theEditor;

    ClassicEditor
      .create(document.querySelector('#agenda_mesyuarat'))
      .then(editor => {
        theEditor = editor;

      })
      .catch(error => {
        console.error(error);
      });


    function getDataFromTheEditor() {
      return theEditor.getData();
    }
    
 function send_1() {
  var testing = "<p><strong>Tilte</strong></p><p><i>123</i></p>";
  CKEDITOR.instances[agenda_mesyuarat].setData(testing);
}
<script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>

<textarea class="form-control" name="agenda_mesyuarat" id="agenda_mesyuarat" value="" title="Agenda Mesyuarat"></textarea><br><br>

<button type="button" id="btn_save" value="Save" onclick="send_1()">Save</button>

Hope someone can guide me on how to solve it. Thanks.


Solution

  • As you are assigning editor instance to theEditor, you can directly use it to set data in ckeditor.

    let theEditor;
    
        ClassicEditor
          .create(document.querySelector('#agenda_mesyuarat'))
          .then(editor => {
            theEditor = editor;
    
          })
          .catch(error => {
            console.error(error);
          });
    
    
        function getDataFromTheEditor() {
          return theEditor.getData();
        }
        
     function send_1() {
      var testing = "<p><strong>Tilte</strong></p><p><i>123</i></p>";
      theEditor.setData(testing);
    }
    <script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>
    
    <textarea class="form-control" name="agenda_mesyuarat" id="agenda_mesyuarat" value="" title="Agenda Mesyuarat"></textarea><br><br>
    
    <button type="button" id="btn_save" value="Save" onclick="send_1()">Save</button>