问题
I am using CK Editor in an app.
<textarea name="contentDetails" id="contentDetails" rows="10" cols="80"></textarea>
But I can't retrieve text from that textarea. I've tried-
var content= $("#contentDetails").text(); //and also .val() & .html()
But content
variable remains empty.
Any idea?
//UPDATE - add my codes below
<script>
CKEDITOR.replace('contentDetails');
$(function () {
$("#submitcontent").click(function (e) {
e.preventDefault();
var content= $("#contentDetails").text();
});
});
</script>
回答1:
Try this:
var text = CKEDITOR.instances.contentDetails.getData();
回答2:
The official CKEditor jQuery adapter guide explains:
// Get the editor data.
var data = $( 'textarea.editor' ).val();
// Set the editor data.
$( 'textarea.editor' ).val( 'My new content' );
回答3:
Here is one more example (based on CKEditor5):
let theEditor;
ClassicEditor
.create(document.querySelector('#contentDetails'))
.then(editor => {
theEditor = editor;
})
.catch(error => {
console.error(error);
});
function getDataFromTheEditor() {
return theEditor.getData();
}
document.getElementById('getdata').addEventListener('click', () => {
alert(getDataFromTheEditor());
});
<script src="https://cdn.ckeditor.com/ckeditor5/10.0.1/classic/ckeditor.js"></script>
<textarea name="contentDetails" id="contentDetails" rows="10" cols="80">
<p>Here goes the initial content of the editor.</p>
</textarea>
<button id="getdata">Print data</button>
回答4:
Ckeditor will replace your textarea with it's own elements and that is where you will need to get the html from. If you inspect the original textarea you will find it empty, the content is actually elsewhere within a bunch of html generated by the editor. Try using inspect element to find a selector for the element that contains the content that you can use. Make sure your jQuery executes after the editor initializes.
回答5:
According to official Documentation : CKEditor Dom Element
Try
textarea = document.getElementById('contentDetails');
textareaNode = new CKEDITOR.dom.element(textarea);
textareaNode.getValue();
来源:https://stackoverflow.com/questions/28379925/get-text-from-ck-editor-textarea-in-jquery