How to trigger the blur event on CKEditor textareas?

心不动则不痛 提交于 2020-05-31 05:17:23

问题


We have some code for validating input on a CKEditor textarea that runs on blur. We add a class of ckeditor_textarea to all textareas that use CKEditor and run this code to attach the necessary functions to the blur event:

$("textarea.ckeditor_textarea").each(function(){
    var textarea_id = $(this).attr("id");
    CKEDITOR.instances[textarea_id].on('blur',function(){
        // Validation functions here
    });
});

This works to fire the validation functions when the blur event happens. But we also need to manually trigger the blur event when the submit button is pressed to run the validation functions on these CKEditor textareas before submitting.

How do you trigger the blur event on a CKEditor textarea? Using jQuery syntax (which of course doesn't work because the CKEditor instance isn't a jQuery object), I'm basically looking for something like this:

$("textarea.ckeditor_textarea").each(function(){
    var textarea_id = $(this).attr("id");
    CKEDITOR.instances[textarea_id].trigger('blur');
});

回答1:


  1. You should not mix jQuery events and CKEDITOR events. If you would like to have blur for CKEDITOR instance, register it:

    ckeInst.on('blur', function(e){

    });

And then, if you really want to trigger blur event, you do it like this:

ckeInst.focusManager.blur( true ); 

Editor is retrived from event (if you have it), or via CKEDITOR.instances['yourCkeName'];




回答2:


For submit validation I would suggest using the updateElement() method within your submit handler, then run your validation code:

Following will update any and all elements using editor on a page:

$('form').on('submit', function(e){
     for (instance in CKEDITOR.instances) {
         CKEDITOR.instances[instance].updateElement();
      }
      // run validation code

});

This also makes sure that the form data is up to date with the editors themselves




回答3:


Based on @charlietfl's answer, I was able to come up with a solution for my situation.

First, I created a function to call that runs the validation code:

function ckeditor_blur_event(textarea_id){
    // validation code  
}

Then, I changed the first block of code in my question to use the new function:

$("textarea.ckeditor_textarea").each(function(){
    var textarea_id = $(this).attr("id");
    ckeditor_blur_event(textarea_id)
});

Finally, I trigger the same validation code when the form is submitted:

$("textarea.ckeditor_textarea").each(function(){
    var textarea_id = $(this).attr("id");
    CKEDITOR.instances[textarea_id].updateElement();
    ckeditor_blur_event(textarea_id)
});



回答4:


The only way which reliably and properly worked for me is:

editor.window.$.frameElement.blur();


来源:https://stackoverflow.com/questions/32831705/how-to-trigger-the-blur-event-on-ckeditor-textareas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!