user115422
user115422

Reputation: 4710

CKEditor 4 (replace by class name) get text area value

I am trying to create a preview function in a CKEditor instance.

I'm using CKEditor 4 and am replacing textareas by class name, the only issue I am facing is that I cannot get the value of the textarea using JavaScript, this is what I've tried so far:

function prev()
    {
        html=document.forms["1_form"]["editor1"].value;
        document.getElementById("prev").innerHTML = html;
    }

and the CKEditor textarea:

<textarea class="ckeditor" onkeydown="prev()"></textarea>

Why doesn't this work? If I disable CKEditor, the script functions as expected, but not with ckeditor enabled. What am I supposed to do?

Thanks!

Edit:

I am now trying to do it with replace and this is the code I'm using: CKEDITOR.replace('editor1'); //new ckeditor instance var editor = CKEDITOR.instances.editor1; //reference to instance

//on `key` event
editor.on('key', function(){

var data = editor.getData(); //reference to ckeditor data
$('#prev').html(data); //update `div` html

});

it works but the only this is, it updates only after the next key is pressed so say the value of the editor is hello world it will show the preview as hello worl what can I do to this code to fix it, please ignore the first set of code.

Upvotes: 1

Views: 7675

Answers (2)

designosis
designosis

Reputation: 5263

For anyone who needs it, here's one way to get the TEXT value of an HTML field (used in this case for a dynamic character counter):

JS ...

CKEDITOR.replace( 'myDoc', {
    width: 605,
    height: 500
});

setInterval("updateCount()", 500);

function updateCount() {
    var str = CKEDITOR.instances.myDoc.getData();
    if (str) {
        var element = CKEDITOR.dom.element.createFromHtml( str );
        var no_html = element.getText();
        $('#myDoc_length').html( no_html.length );
    }
}

... with HTML ...

<textarea id="myDoc"></textarea>
<span id="myDoc_length">0</span> characters

Upvotes: 1

antyrat
antyrat

Reputation: 27765

This is because CKEDITOR replace your <textarea> into <div> with contenteditable="true" attribute and there is no value property in DOM for <div> element.

You need to add event listener to CKEDITOR instance, not to DOM element, for example:

// check if editor is ready
CKEDITOR.on( 'instanceCreated', function( e ) {

        // check if DOM is ready
        e.editor.on( 'contentDom', function() {

            // bind "keydown" event to CKEDITOR
            e.editor.document.on('keydown', function( event ) {

                // write editor content into "prev" element
                document.getElementById( "prev" ).innerHTML = e.editor.getData();
            }
        );
    });
});

Upvotes: 4

Related Questions