首页 > 解决方案 > 使用 jQuery 表单验证时,CKeditor 实例 updateElement() 无法正常工作

问题描述

我有一个包含三个 texareas 的表单,名称和 id 都为description,missionvision. 这三个文本区域都有CKeditor。

我需要验证三个文本区域以获得内容。为了使用 CKeditor 的内容更新 textareas,建议使用以下代码。

for(var instanceName in CKEDITOR.instances)
{
    CKEDITOR.instances[instanceName].updateElement();
}

我将上述代码集成到我的 jquery 表单验证功能中,如下所示:-

这是我的 jquery 验证功能

$("#editPostForm").validate({
  ignore: "",
  rules: {
    description: {
      required      : true,
      minlength     : 3
    },
    mission: {
      required      : true,
      minlength     : 3
    },
    vision: {
      required      : true,
      minlength     : 3
    }
  },
  messages: {
    description: {
      required      : "Please enter description of about us",
      minlength     : "About us should be atleast 3 characters"
    },
    mission: {
      required      : "Please enter description of mission",
      minlength     : "Mission should be atleast 3 characters"
    },
    vision: {
      required      : "Please enter description of vision",
      minlength     : "Vision should be atleast 3 characters"
    }
  },
  errorPlacement: function (error, element) {
    if($(element).prop('type') == 'textarea')
    {
      if($(element).prop('name') == 'description')
      {
        error.insertAfter($('#cke_desc'));
      }
      else if ($(element).prop('name') == 'mission') 
      {
        error.insertAfter($('#cke_mission'));
      }
      else if ($(element).prop('name') == 'vision') 
      {
        error.insertAfter($('#cke_vision'));
      }
      else
      {
        error.insertAfter($(element));
      }
    }
  },
  submitHandler : function(form){
    for(var instanceName in CKEDITOR.instances)
    {
      CKEDITOR.instances[instanceName].updateElement();
    }
    form.submit();
  }
});

这似乎工作得很慢。例如,如果我从某处复制内容并粘贴到编辑器上,然后单击提交按钮,我会收到验证错误,尽管编辑器中有内容。但是当我第二次立即单击按钮时,表单被提交。

考虑另一种情况。我再次以编辑模式访问表单,看到数据(之前保存的)显示在编辑器中。我制作了一个 ctrl + A 来选择编辑器的全部内容并删除内容。当我单击提交按钮时,表单被提交,因为编辑器尚未更新内容已被删除且当前为空的文本区域。

但是,假设我第一次访问编辑器并单击提交按钮而没有写任何内容,验证错误仍然显示错误消息。

我想知道为什么 updateElement() 需要这么长时间才能工作?

标签: jqueryckeditorjquery-validate

解决方案


推荐阅读