How to check whether CKEditor has some text in it?
Asked Answered
C

8

23

I have an HTML form with a few fields. One of them is a textarea managed by CKEditor.

When the user wants to submit the form, I want to check whether he entered values in all the fields.

I know how I can check if CKEditor control has anything in it, but it could be "empty" HTML tags without any text in it.

How do I check for text?

Server side I'm using something like PHP's trim(strip_tags($content)), so I'd like to have the same in JavaScript.

A solution using jQuery would also be usable.

Chong answered 18/7, 2010 at 21:2 Comment(0)
D
34

This will work:

$("#editorContainer iframe").contents().find("body").text();

That will contain only the text, and none of the html tags.

UPDATE

It definitely works on the CKEditor demo page. Use Firefox and Firebug, go to the Firebug console, and type in:

$("#demoInside iframe").contents().find("body").text();

The console will print out the text in the editor, with no html tags. Make sure you have the selector correct in your particular application. You can test your selector like this:

$("#demoInside iframe").contents().find("body").length;

That should equal 1. If it's 0, your selector is wrong.

UPDATE 2

Again, my code is still correct, and it still works on that page. You just need the right selector. On the page you linked to, it is a <span> with id cke_editor1. That particular page does not make use of jQuery, so it requires some additional work to prove this sample works. Install FireQuery, "jqueryify" the page, and then do this in the Firebug console (note you have to use jQuery and not $. That's how FireQuery works).

jQuery("#cke_editor1 iframe").contents().find("body").text();

In short, make sure you have the right selector to get to your iframe. Whether you create your CKEditor from a <div> or a <textarea> is not important. As long as you can select the <iframe> that CKEditor injects into the DOM, you can use .contents().find("body").text() to get the text of that iframe. Have you tested your jquery selector to see if .length == 1?

Dedicate answered 18/7, 2010 at 21:16 Comment(4)
Doesn't seem to work, I get an empty string even if I have some text typed into control. I tried replacing #editorContainer with #editor1 as that is the ID of textarea, but that does not work either.Coax
Demo replaces DIV, while my code replaces TEXTAREA. Could you tell me which selector to use on CKEditor sample page: nightly.ckeditor.com/latest/ckeditor/_samples/… ? This would help me determine what should I use in my code. Thanks.Coax
I know this question is old, but I'm curious what would select the val() as well, because the .text() just pulls the the text but none of the html or formatting.Electronic
@SamuelMeacham - Awesome answer bro and @Electronic - .html() works like a charm if one requires the complete HTMLCoccidiosis
A
17

CKeditor has its own built in function for retrieving data in a text editor:

function CheckForm(theForm) 
{
    textbox_data = CKEDITOR.instances.mytextbox.getData();
    if (textbox_data==='')
    {
        alert('please enter a comment');
    }
}

Documentation

Architect answered 9/2, 2015 at 18:34 Comment(1)
I think you meant if (textbox_data === '').Brander
B
6

You can use the following snippet to check if the ckeditor has some text.

var _contents = CKEDITOR.instances.editor1.document.getBody().getText();
if (_contents == '') {
    alert('Please provide the contents.') ;
}
Brooklime answered 7/3, 2018 at 14:26 Comment(1)
Yeah. I have added .trim() at the end. .getText().trim();Lashio
B
1

CKEditor 5 - Classic editor

This is an old question but, since it's one of the first results in google, i think it would be helpful to update the answer for the latest versions of ckeditor, in my case ckeditor 5 version 11.0.1

The problem with ckeditor 5 is even when it's/looks empty, when submitting the form, it does'nt send an empty value as you may expect, but instead it send this string :

<p>&nbsp;</p>

It's not what you want, especially when you want set some validations rules on the server side.

To avoid this headache, i use this snippet of code based on light-flight answer:

$(document).ready(function() {

    var editorContainer = document.querySelector('#editor');

    var check_if_empty = function(val) {

        return $.makeArray($(val)).every(function(el) {

            return el.innerHTML.replace(/&nbsp;|\s/g, '').length === 0;
        });
    };

    var clear_input_if_empty_content = function(input) {

        var $form = $(input).parents('form');

        $form.on('submit', function() {

            if (check_if_empty($(input).val())) {

                $(input).val('');
            }
        });
    };

    ClassicEditor.create( editorContainer )
        .then(function(editor) {
            clear_input_if_empty_content(editorContainer)
        })
        .catch(function(error) {
            console.log(error);
        });
});
Bramble answered 9/8, 2018 at 11:29 Comment(1)
I guess there is a more intuitive way to check this, in the API there is somthing called getDataWithoutFiller(), and the <p>&nbsp;</p> is generated out from NBSP_FILLER(), but those bot functions wont work on the editor instance!Hogue
S
1

<script>
CKEDITOR.replace('messagechat');

var feedback = CKEDITOR.instances.messagechat.document.getBody().getChild(0).getText(); 
// get Data
alert(feedback);
</script>
Sarsenet answered 17/9, 2019 at 6:54 Comment(1)
Although this code might solve the problem, a good answer should also explain how/why the code helps.Tripping
O
1

We work in CKEditor 5 with long texts with embeded pictures and function editor.getData() for long document is heavy. It is too slow to be called with every change just to ensure if editor is empty.

So here is my solution:

isEditorEmpty(editor) {
    // Get root node of editor document
    const root = editor.model.document.getRoot();
    
    // Root node is empty
    if (root.childCount === 0 || root.isEmpty) {
        return true;
    }
    
    // Root contains more then one initial paragraph 
    if (root.childCount >= 2 ) {
        return false
    }

    // Root contains one empty paragraph or one node with content
    return !editor.getData();
}

// Initialization and event binding
ClassicEditor.create( el, config )
    .then( editor => {
        editor.model.document.on('change:data', () => {
            if ( isEditorEmpty(editor) ) {
                doSomething_itIsEmpty();
            } else {
                doSomethingElse_itHasContent();
            }
        });
    })
; 

I hope it would help you. See details in documentation of isEmpty property of document node.

Orthogenic answered 28/7, 2023 at 18:24 Comment(0)
P
0

We use prototype, with that library and the following addition:

Element.addMethods({  
  getInnerText: function(element) {
    element = $(element);
    return element.innerText && !window.opera ? element.innerText
      : element.innerHTML.stripScripts().unescapeHTML().replace(/[\n\r\s]+/g, ' ');
  }
});

(Thanks to Tobie Langel)

I was able to use the following function to determine whether any actual text was inside CKEditor:

function editorEmpty(instanceName){

    var ele = (new Element('div')).update(CKEDITOR.instances[instanceName].getData()); 

    return (ele.getInnerText() == '' || innerText.search(/^(&nbsp;)+$/i) == 0);
}

Note the test for &nbsp; as well - often when the editor appears empty, it actually contains something like: <p>&nbsp;</p>.

Photobathic answered 14/8, 2010 at 4:34 Comment(0)
P
0

You can check if the field has any content by first updating all the instances, first, create a function to do that:

function updateInstances(){
    for( instance in CKEDITOR.instances )`
CKEDITOR.instances[instance].updateElement();
}

then, on submit,

just call the updateInstances() function, after that you can test the field normally just like,

var fieldValue = $.trim($(document).find('textarea#field_ID').val());
if(fieldValue.length != 0){
//your code
}
Polygenesis answered 21/5, 2023 at 18:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.