简体   繁体   中英

How to trigger the blur event on CKEditor textareas?

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. 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'];

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

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

对我来说可靠和正确工作的唯一方法是:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM