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

发布于 2024-09-10 02:06:01 字数 273 浏览 9 评论 0原文

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

当用户想要提交表单时,我想检查他是否在所有字段中输入了值。

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

如何检查文本?

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

小糖芽 2024-09-17 02:06:01

这将起作用:

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

它将仅包含文本,而不包含任何 html 标签。

更新

它绝对可以在CKEditor演示页面上运行。使用 Firefox 和 Firebug,进入 Firebug 控制台,然后输入:

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

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

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

它应该等于 1。如果它是 0,则您的选择器是错误的。

更新2

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

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

简而言之,确保您有正确的选择器来访问您的 iframe。无论您是从

还是

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?

哑剧 2024-09-17 02:06:01

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

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

文档

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

世界如花海般美丽 2024-09-17 02:06:01

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

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

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.') ;
}
定格我的天空 2024-09-17 02:06:01

CKEditor 5 - 经典编辑器

这是一个老问题,但是,由于它是谷歌的第一个结果之一,我认为更新最新版本的ckeditor的答案会很有帮助,在我的例子中是ckeditor 5版本11.0。 1

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

<p> </p>

这不是您想要的,尤其是当您想在服务器端设置一些验证规则时。

为了避免这个头痛,我使用了这段基于 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(/ |\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);
        });
});

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> </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(/ |\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);
        });
});
孤城病女 2024-09-17 02:06:01
<script>
CKEDITOR.replace('messagechat');

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

var feedback = CKEDITOR.instances.messagechat.document.getBody().getChild(0).getText(); 
// get Data
alert(feedback);
</script>
聚集的泪 2024-09-17 02:06:01

我们在 CKEditor 5 中处理带有嵌入图片的长文本,并且长文档的函数 editor.getData() 非常繁重。每次更改时都调用它来确保编辑器是否为空,这太慢了。

所以这是我的解决方案:

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

希望对您有所帮助。请参阅 isEmpty 文档 的详细信息文档节点。

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.

梅倚清风 2024-09-17 02:06:01

我们使用原型,以及该库和以下附加内容:(

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

感谢 Tobie Langel< /a>)

我能够使用以下函数来确定 CKEditor 中是否有任何实际文本:

function editorEmpty(instanceName){

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

    return (ele.getInnerText() == '' || innerText.search(/^( )+$/i) == 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(/^( )+$/i) == 0);
}

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

彼岸花似海 2024-09-17 02:06:01

您可以通过首先更新所有实例来检查该字段是否有任何内容,首先,创建一个函数来执行此操作:

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

然后,在提交时,

只需调用 updateInstances() 函数,之后您可以测试该字段通常就像,

var fieldValue = $.trim($(document).find('textarea#field_ID').val());
if(fieldValue.length != 0){
//your code
}

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文