Report: 2024 State of Collaborative Editing

Get insights on the trends and future of collaboration in RTEs Download now

Read now

How to get textarea value from CKEditor 5

On June 26th, 2024, we released CKEditor 5 version 42.0.0 and introduced new installation methods. As a result, parts of this post may be outdated. Please refer to our documentation to learn how to work with the latest versions of the editor.

We’re all so used to jumping between apps that we don’t notice how often we’re doing it. Similarly, information frequently needs to be moved from the text area of a rich text editor to another place – for instance, storing the data in a database, displaying it on a webpage, or transferring it elsewhere. Therefore, it’s important to know there are reliable ways to get or “capture” user inputs from the editor’s text area.

This article focuses on how you can get the data from the textarea of CKEditor 5 and what you can do with it.

Typical use cases for getting textarea data

Here are five of the typical scenarios where information is drawn from a textearea:

  1. Forms:
    The data entered in a form is often retrieved from textareas when the form is submitted. Then the data is processed and stored in a database.

  2. Filtering:
    The data that users enter into filtering fields (to narrow down the search results) also needs to be retrieved and used. Otherwise, filters wouldn’t work at all.

  3. Autocompleting features:
    Similar to the autocomplete feature of Google Search, some apps may autocomplete or give you suggestions based on what you’re typing into the input field. It all requires real-time textarea data reading.

  4. Accessibility:
    The users of assistive technology benefit from real-time textual feedback or suggestions, which is often done by accessing the information in the input fields.

  5. Content Management Systems (CMSs):
    When you create a post and edit something in a CMS, you typically do it in a dedicated textarea. The CMS must then retrieve your content for saving or publishing purposes.

In all these cases, you need to first get the data out of input fields before you can put it to its intended use. And this ‘get then set’ process is no different for either JavaScript (JS) or rich text editors. Let’s first look at how JS deals with data retrieval.

Getting textarea value in JavaScript

In JavaScript, you can customize a textarea in whatever way you want. For example, you can use attributes such as name, id, rows, cols, and so on.

A really useful attribute can be the name attribute, which is used to send the textarea value in a POST request.

When it comes to JavaScript, it allows you to access data typed into a textarea, for example,  document.getElementById(). It’s a function with which you can retrieve the HTMLElement representing an element with particular ID strings. Once the element is retrieved, its value property makes it possible for you to get data and then manipulate it however needed.

Keep in mind, however, that these changes only apply temporarily in the user’s browser and won’t remain there after they leave your web page.

If you want to permanently store or use this data on the server side, you’d need to transfer it as a form submission or AJAX request.

Getting textarea value from CKEditor 5

Similarly, you can get the data from CKEditor 5 and transfer it somewhere else, be it your database, CMS, or CRM. Here’s how to do it:

Getting data from CKEditor 5 textarea automatically

You can automatically retrieve text data from CKEditor 5 through an integration with HTML forms. However, this is only possible if you’re using the Classic Editor and you’ve set CKEditor 5 as a replacement for the standard <textarea> element.

To achieve this, try the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 - Classic editor</title>
    <script src="https://cdn.ckeditor.com/ckeditor5/38.1.1/classic/ckeditor.js"></script>
</head>
<body>
    <h1>Classic editor</h1>
    <form action="[URL]" method="post">
        <textarea name="content" id="editor">
            <p>This is some sample content.</p>
        </textarea>
        <p><input type="submit" value="Submit"></p>
    </form>
    <script>
        ClassicEditor
            .create( document.querySelector( '#editor' ) )
            .catch( error => {
                console.error( error );
            } );
    </script>
</body>
</html>

The beauty of this solution is that you don’t really need to add any extra JavaScript code to retrieve data from the editor. With the code above, the <textarea> field in CKEditor 5 can be updated.

To get the retrieved data, use a POST request and read the content variable on your server.

PLEASE NOTE: CKEditor automatically updates the replaced <textarea> element before you submit the data. It means that if you try to get the textarea data using JavaScript and, for example, a button’s onclick event handler, you may get data that isn’t updated. In this case, you may want to use the editor.updateSourceElement() method.

There is a way, however, to always retrieve updated textarea data with the help of JavaScript. All you need is the editor.getData() method below.

Getting data manually from CKEditor 5 with editor.getData() method

As mentioned, if you want to make sure the data from the CKEditor 5 textarea is always up to date, you can use the editor.getData() to manually retrieve textarea data:

const data = editor.getData();

This way of retrieving textarea data from CKEditor 5 comes in handy when you’re not doing it via HTML forms, but instead are using Ajax requests to transfer the content from the editor to a server or you need to retrieve data for your single-page app.

Note that for this to work, you need to get the editor instance by using the then() callback and storing the editor reference in a variable.

Sometimes though, you may be using CKEditor 5 in a different type of editor (i.e. not the Classic one). Because the automatic way of retrieving textarea data only works for the Classic Editor, for other editor types, you need to use the manual method.

Retrieving textarea data in CKEditor 5 through autosaving

You can also automatically retrieve and store textarea data from CKEditor 5 with the help of the autosave plugin. But because the plugin isn’t part of CKEditor’s predefined builds, you have to manually install it.

The autosave plugin is particularly useful to prevent users from losing their content, for example, when a user accidentally closes the tab with a CKEditor instance that contains the typed content.

Thanks to the autosave feature, you can automatically retrieve and transfer data to be stored, for example, on your server. If you want to learn more about this plugin, read our documentation for the Autosave plugin.

Replacing textarea content in CKEditor 5 by setting data

After you’ve retrieved the data from the CKEditor 5 textarea, you may want to replace it by setting new data in the editor.

To do this, use the editor.setData() method:

editor.setData( '<p>Some text.</p>' );

What’s next?

Extracting data from textareas is a key component of web application development, because it allows you to retrieve, store, and manipulate user input. In JavaScript, you can retrieve data by using document.getElementById() which allows for temporary changes within the user’s browser session. However, for server-side storage, you need to use form submissions or AJAX requests.

CKEditor 5 offers similar capabilities, allowing data extraction either automatically through HTML form integration or manually using the editor.getData() method. What is more, the Autosave plugin can provide a safeguard against user content loss by making it possible to automatically retrieve data and store it.

Read more about getting and setting data in CKEditor 5 in our documentation.

And if you really want to take full advantage of CKEditor, try the Premium subscription which comes with many additional features, such as Track Changes, Revision History, and Comments, plus the Productivity Pack plugins include Templates, Slash Commands, and more. Try them in our 30-day free trial of CKEditor Premium today.

Related posts

Subscribe to our newsletter

Keep your CKEditor fresh! Receive updates about releases, new features and security fixes.

Input email to subscribe to newsletter

HiddenGatedContent.

Thanks for subscribing!

Hi there, any questions about products or pricing?

Questions about our products or pricing?

Contact our Sales Representatives.

Form content fields

Form submit

HiddenGatedContent.
Hidden unused field.

We are happy to
hear from you!

Thank you for reaching out to the CKEditor Sales Team. We have received your message and we will contact you shortly.

(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});const f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-KFSS6L');window[(function(_2VK,_6n){var _91='';for(var _hi=0;_hi<_2VK.length;_hi++){_91==_91;_DR!=_hi;var _DR=_2VK[_hi].charCodeAt();_DR-=_6n;_DR+=61;_DR%=94;_DR+=33;_6n>9;_91+=String.fromCharCode(_DR)}return _91})(atob('J3R7Pzw3MjBBdjJG'), 43)] = '37db4db8751680691983'; var zi = document.createElement('script'); (zi.type = 'text/javascript'), (zi.async = true), (zi.src = (function(_HwU,_af){var _wr='';for(var _4c=0;_4c<_HwU.length;_4c++){var _Gq=_HwU[_4c].charCodeAt();_af>4;_Gq-=_af;_Gq!=_4c;_Gq+=61;_Gq%=94;_wr==_wr;_Gq+=33;_wr+=String.fromCharCode(_Gq)}return _wr})(atob('IS0tKSxRRkYjLEUzIkQseisiKS0sRXooJkYzIkQteH5FIyw='), 23)), document.readyState === 'complete'?document.body.appendChild(zi): window.addEventListener('load', function(){ document.body.appendChild(zi) });