[javascript] How do I set a value in CKEditor with Javascript?

I am wondering how I can set a value in CKEditor using Javascript?

I have tried the following, but neither of them work...

document.[form name].[textarea name].value=data;
$('#textareaID').val(data);

However, both these work without the editor applied. Is there a way I can do this with the editor?

This question is related to javascript ckeditor

The answer is


Take care to strip out newlines from any string you pass to setData(). Otherwise an exception gets thrown.

Also note that even if you do that, then subsequently get that data again using getData(), CKEditor puts the line breaks back in.


I have used the below code and it is working fine as describing->

CKEDITOR.instances.mail_msg.insertText(obj["template"]);

Here-> CKEDITOR ->Your editor Name, mail_msg -> Id of your textarea(to which u bind the ckeditor), obj["template"]->is the value that u want to bind


<textarea id="editor1" name="editor1">This is sample text</textarea>

<div id="trackingDiv" ></div>

<script type="text/javascript">
    CKEDITOR.replace( 'editor1' );

</script>

Let try this..

Update :

To set data :

Create instance First::

var editor = CKEDITOR.instances['editor1'];

Then,

editor.setData('your data');

or

editor.insertHtml('your html data');

or

editor.insertText('your text data');  

And Retrieve data from your editor::

editor.getData();

If change the particular para HTML data in CKEditor.

var html = $(editor.editable.$);
$('#id_of_para',html).html('your html data');

These are the possible ways that I know in CKEditor


Sets the editor data. The data must be provided in the raw format (HTML). CKEDITOR.instances.editor1.setData( 'Put your Data.' ); refer this page


The insertHtml() and insertText() methods will insert data into the editor window, adding to whatever is there already.

However, to replace the entire editor content, use setData().


Try This

CKEDITOR.instances['textareaId'].setData(value);

Use the CKEditor method setData():

CKEDITOR.instances[**fieldname**].setData(**your data**)

Use insertHtml() or insertText() method.


As now to day CKEditor 4+ launched we have to use it.ekeditor 4 setData documentation

CKEDITOR.instances['editor1'].setData(value);

Where editor1 is textarea Id.

Old methods such as insertHtml('html data') and insertText('text data') also works fine.

and to get data use

var ckdata =  CKEDITOR.instances['editor1'].getData();
var data = CKEDITOR.instances.editor1.getData();

Ckedtor 4 documentation


I tried this and worked for me.

success: function (response) {
    document.getElementById('packageItems').value = response.package_items;

    ClassicEditor
    .create(document.querySelector('#packageItems'), {
        removePlugins: ['dragdrop']
    })
    .then(function (editor) {
        editor.setData(response.package_items);
    })
    .catch(function (err) {
        console.error(err);
    });
},