How to get value of CKEditor 5?
Asked Answered
S

5

15

I want to be able to return the value of the CKEditor textarea, and also write my text inside it.

I used CKEditor 5 CDN. First this my code for the textarea it works fine

<script src="https://cdn.ckeditor.com/ckeditor5/1.0.0-alpha.1/classic/ckeditor.js"></script>

<textarea class="inputStyle" id="editor" name="content" placeholder="Write your email.."></textarea>
<script>ClassicEditor.create(document.querySelector('#editor')).catch( error => { console.error( error );  } ); </script>

I used to get the data from the textarea before the CKEditor by:

var text = $('textarea#editor').val();

and set the data by:

$('textarea#editor').html("");

but i'm lost now? i tried many ways... what is the correct way?

Sphery answered 30/10, 2017 at 11:19 Comment(1)
share more code, how you created ckedit, creating instance and to get dataSalzburg
B
40

You need to get or save the editor created and then use the getData() function. You can add a .then() on creation to save your editor.

    var myEditor;

    ClassicEditor
        .create( document.querySelector( '#editor' ) )
        .then( editor => {
            console.log( 'Editor was initialized', editor );
            myEditor = editor;
        } )
        .catch( err => {
            console.error( err.stack );
        } );

and then get data using

myEditor.getData();
Brendonbrenk answered 30/10, 2017 at 12:7 Comment(5)
... while myEditor.setData() is for setting the data in the editor. Keep in mind that editor data does not save automatically to textarea, so before you submit the form, you should do something like $('textarea#editor').html( myEditor.getData() ).Tareyn
I tried exactly that, as follows, and got "cannot read property getData of undefined. This is my code: var editorinstance; ClassicEditor.create(document.querySelector('#editor')) .then(editor => { editorinstance = editor; }).catch(error => { console.error(error); }); alert(editorinstance.getData());Purpleness
@Purpleness you probably get an error on create. Check your console for the error. Is your text area id="editor"??Brendonbrenk
For those, who get respond that getData() is not a function or is undefined, it is because you need to wait till ckeditor will load to get its value.. document.addEventListener("DOMContentLoaded", function(event){console.log(my_editor.getData())});Alaniz
I am very new to this, Unable to figure out, where I can keep this code, Can anyone please tell me this? Thank youChart
C
6

I use another way to work with ckEditors.

First thing is - I don't want to initialize ckEditor in every page where I use Editors.

Second thing is - Sometimes I need to access to ckEditors by name.

So, there is my point of view:

Add to your Layout:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.ckeditor.com/ckeditor5/11.2.0/classic/ckeditor.js"></script>

Use it in your view:

<input type="text" name="tbxQuestion" class="ck-classic"/>
<input type="text" name="tbxAnswer1" class="ck-classic-min"/>
<input type="text" name="tbxAnswer2" class="ck-classic-min"/>
<input type="text" name="tbxAnswer3" class="ck-classic-min"/>

A little css:

.ck-classic {
    display: none;
}

.ck-classic-min {
    display: none;
}

Add tiny JS to Layout (better way to add as separated JS file):

const ckEditorClassicOptions = {
    toolbar: ['heading', '|', 'bold', 'italic', 'bulletedList', 'numberedList', 'blockQuote', 'link', 'insertTable', 'undo', 'redo'],
    heading: {
        options: [
            { model: 'paragraph', title: 'Параграф' },
            //{ model: 'heading1', view: 'h1', title: 'Heading 1' },
            { model: 'heading2', view: 'h2', title: 'Заголовок 2' },
            { model: 'heading3', view: 'h3', title: 'Заголовок 3' },
            { model: 'heading4', view: 'h4', title: 'Заголовок 4' },
            { model: 'heading5', view: 'h5', title: 'Заголовок 5' }
        ]
    }
};

const ckEditorClassicOptionsMin = {
    toolbar: ['bold', 'italic']
};

var allCkEditors = [];
$(document).ready(function() {
    // Initialize All CKEditors
    allCkEditors = [];

    var allHtmlElements = document.querySelectorAll('.ck-classic');
    for (var i = 0; i < allHtmlElements.length; ++i) {
        ClassicEditor
            .create(allHtmlElements[i], ckEditorClassicOptions)
            .then(editor => {
                allCkEditors.push(editor);
            })
            .catch(error => {
                console.error(error);
            });
    }

    allHtmlElements = document.querySelectorAll('.ck-classic-min');
    for (var j = 0; j < allHtmlElements.length; ++j) {
        ClassicEditor
            .create(allHtmlElements[j], ckEditorClassicOptionsMin)
            .then(editor => {
                allCkEditors.push(editor);
            })
            .catch(error => {
                console.error(error);
            });
    }

});

function ckEditor(name) {
    for (var i = 0; i < allCkEditors.length; i++) {
        if (allCkEditors[i].sourceElement.id === name) return allCkEditors[i];
    }

    return null;
}

And after that get Data from where you need:

ckEditor("tbxQuestion").getData()
Chiliasm answered 25/2, 2019 at 10:54 Comment(0)
B
4

Actually, there are lots of ways to achieve this but this way is very short and optimized and also this setup can work perfectly with single as well as multiple <textarea>.

document.querySelectorAll('.ckeditor').forEach(e => {
  ClassicEditor
    .create(e)
    .then(editor => {
      editor.model.document.on('change:data', () => {
        e.value = editor.getData();
      });
    })
    .catch(error => {
      console.error(error);
    });
})
<script src="https://cdn.ckeditor.com/ckeditor5/29.0.0/classic/ckeditor.js"></script>

<!--Native Text Field-->
<textarea class="ckeditor"></textarea>
Beckmann answered 18/7, 2021 at 14:47 Comment(1)
Yes this should be accepted and upvoted. thx alot manCurvet
W
0

Using the developer console, I found this to work for me:

CKEDITOR.instances.(textarea_id).getData();

Whoredom answered 21/4, 2019 at 15:7 Comment(0)
K
0

Most easiest way:

//global vars
var CKEditorArray = [];//CKEditor access array

//initialize function
function CKEditorInit(selector_name){
    ClassicEditor
        .create(document.querySelector(selector_name),{
            //some options
            toolbar: {
                items: [
                    'undo', 'redo', '|',
                    'fontSize', 'bold', 'italic', 'underline', '|',
                    'alignment', 'bulletedList', 'numberedList', '|',
                    'outdent', 'indent', '|',
                    'fontColor', 'fontBackgroundColor', '|',
                    'sourceEditing'
                ],
            },
        })
        .then(editor => {
            console.log(editor);
            CKEditorArray[selector_name] = editor;//save editor with selector name as index to array
        })
        .catch(error => {
            console.error(error);
        });
}

//then we need to init CKEditor, we just call function
CKEditorInit('#textarea-id');

//access to Editor like:
alert(CKEditorArray['#textarea-id'].getData());

Keniakenilworth answered 17/10, 2021 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.