Javascript 如何检查CKEditor中是否有一些文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3277250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:59:45  来源:igfitidea点击:

How to check whether CKEditor has some text in it?

javascriptckeditorfckeditor

提问by Milan Babu?kov

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

我有一个包含几个字段的 HTML 表单。其中之一是由 CKEditor 管理的 textarea。

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.

我知道如何检查 CKEditor 控件中是否有任何内容,但它可能是没有任何文本的“空”HTML 标记。

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.

服务器端我正在使用类似 PHP 的 trim(strip_tags($content)) 之类的东西,所以我想在 JavaScript 中使用相同的东西。

A solution using jQuery would also be usable.

使用 jQuery 的解决方案也可以使用。

回答by Samuel Meacham

This will work:

这将起作用:

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

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

那将只包含文本,不包含任何 html 标签。

UPDATE

更新

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

它绝对适用于CKEditor 演示页面。使用 Firefox 和 Firebug,转到 Firebug 控制台,然后输入:

$("#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:

控制台将打印出编辑器中的文本,没有 html 标签。确保在您的特定应用程序中选择器正确。您可以像这样测试您的选择器:

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

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

那应该等于 1。如果它是 0,那么你的选择器是错误的。

UPDATE 2

更新 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 jQueryand not $. That's how FireQuery works).

同样,我的代码仍然正确,并且在该页面上仍然有效。您只需要正确的选择器。在您链接到的页面上,它是一个<span>with id cke_editor1。该特定页面未使用 jQuery,因此需要一些额外的工作来证明此示例有效。安装FireQuery,“jqueryify”页面,然后在 Firebug 控制台中执行此操作(注意您必须使用jQuery而不是$。这就是 FireQuery 的工作原理)。

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?

简而言之,请确保您有正确的选择器来访问 iframe。你是从 a<div>还是 a创建你的 CKEditor<textarea>并不重要。只要你可以选择<iframe>CKEditor注入到DOM中的那个,你就可以使用它.contents().find("body").text()来获取该iframe的文本。你有没有测试过你的 jquery 选择器,看看是否.length == 1

回答by a coder

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

CKeditor 有自己的内置函数,用于在文本编辑器中检索数据:

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

Documentation

文档

回答by Jamal Abdul Nasir

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

您可以使用以下代码段来检查 ckeditor 是否有一些文本。

var _contents = CKEDITOR.instances.editor1.document.getBody().getText();
if (_contents == '') {
    alert('Please provide the contents.') ;
}

回答by user3230794

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

var feedback = CKEDITOR.instances.messagechat.document.getBody().getChild(0).getText(); 
// get Data
alert(feedback);
</script>

回答by chebaby

CKEditor 5 - Classic editor

CKEditor 5 - 经典编辑器

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

这是一个老问题,但由于它是谷歌的第一个结果之一,我认为更新最新版本的 ckeditor 的答案会很有帮助,在我的情况下是ckeditor 5 版本 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 :

ckeditor 5 的问题是,即使它是/看起来是空的,在提交表单时,它也不会像您期望的那样发送空值,而是发送此字符串:

<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-flightanswer:

为了避免这种头痛,我使用了这个基于light-flight答案的代码片段:

$(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);
        });
});

回答by Michael Robinson

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:

我能够使用以下函数来确定 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>.

还要注意测试&nbsp;- 通常当编辑器显示为空时,它实际上包含如下内容:<p>&nbsp;</p>