Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset CKEditor5 form

Sorry if this has been discussed before, but I have searched exhaustively and only found solutions to the older version, not 5. I want to have two buttons for my forms, SEND and RESET. When someone clicks on the reset button I want the form to be clear of all input. I know in the older version I could have done the following:

CKEDITOR.instances['#editor'].setData('');

But this doesn't work with version 5. So I tried

$("#reset").click(function() {
     $('.ck-editor__editable').html( '' );
});

This works and clears up the form. But the problem is the data that just cleared reappears as soon as you click back on the form after clearing it. Please see below for the full code.

Thank you in advance for your help

<html>
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 - Classic editor</title>

</head>
<body>
<style>
.ck-editor__editable {
    min-height: 200px;
}
</style>
    <h1>Classic editor</h1>
    <textarea name="content" id="editor"></textarea>
	<button id="getdata">Print data</button>
	<button id="reset">Reset data</button>
	<div>
		<p>The Textarea output goes here</p>
		<div class="form-output"></div>
	</div>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.ckeditor.com/ckeditor5/1.0.0-beta.2/classic/ckeditor.js"></script>
    <script>

$(function(){
let theEditor;

ClassicEditor
    .create( document.querySelector( '#editor' ) , {
			toolbar: [ 'heading', '|' , 'bold', 'italic', 'underline', 'bulletedList', 'numberedList', 'blockQuote', 'alignment', 'link', 'undo', 'redo', '' ],
			heading: {
				options: [
					{ model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
					{ model: 'heading2', view: 'h2', title: 'Heading', class: 'ck-heading_heading2' },
					{ model: 'heading3', view: 'h3', title: 'Sub Heading', class: 'ck-heading_heading3' }
				]
			}
		})
    .then( editor => {
        theEditor = editor; // Save for later use.
    } )
    .catch( error => {
        console.error( error );
    } );

function getDataFromTheEditor() {
    return theEditor.getData();
}

document.getElementById( 'getdata' ).addEventListener( 'click', () => {
	form_data = getDataFromTheEditor();
    //alert( form_data );
} );
		showData = $('#getdata');
		showData.click(function(){
			$(document).ready(function() {
				$('.form-output').html( form_data );
			});
		});
		
		$("#reset").click(function() {
			$('.ck-editor__editable').html( '' );
		});		
});
</script>
	
</body>
</html>
like image 732
user3659161 Avatar asked Jan 29 '23 07:01

user3659161


1 Answers

Instead of

$('.ck-editor__editable').html( '' );

use

theEditor.setData( '' );

It's almost the same as in v4 except that you have to save the reference to the created editor (as you perfectly did) because there's no global editor registry in v5.

like image 138
oleq Avatar answered Jan 31 '23 09:01

oleq