Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text at the cursor position to a CKEditor using jQuery

I'm trying to add a piece of text to an existing CKEditor using jQuery. This needs to be done when a link is clicked.

I tried this solution, which works for regular textareas, but not for CKEditor:

jQuery.fn.extend({   insertAtCaret: function(myValue) {     return this.each(function(i) {       if (document.selection) {         //For browsers like Internet Explorer         this.focus();         sel = document.selection.createRange();         sel.text = myValue;         this.focus();       } else if (this.selectionStart || this.selectionStart == '0') {         //For browsers like Firefox and Webkit based         var startPos = this.selectionStart;         var endPos = this.selectionEnd;         var scrollTop = this.scrollTop;         this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);         this.focus();         this.selectionStart = startPos + myValue.length;         this.selectionEnd = startPos + myValue.length;         this.scrollTop = scrollTop;       } else {         this.value += myValue;         this.focus();       }     })   } }); 

There is also an option to use: $('#editor').val(), but this appends the text at the end or the beginning and not at the cursor.

So, is there a way to accomplish this?

like image 657
Phoenix Avatar asked Apr 19 '12 08:04

Phoenix


People also ask

How to insert text in CKEditor using JavaScript?

If you want to insert some HTML tagged text that retains the style of surrounding text you should use insertElement. var oEditor = CKEDITOR. instances. yourEditorID; var html = "<a href="#">my anchor</a>"; var newElement = CKEDITOR.

Does Ckeditor use jquery?

Thanks to these changes CKEditor 4 automatically works with the official jQuery Form Plugin for Ajax-based forms. It does not require any action from the developer's side to support it.

How do I get Ckeditor data?

If you need to get the actual data from CKEditor 4 at any moment using JavaScript, use the editor. getData() method as described above.


2 Answers

You should use this

$.fn.insertAtCaret = function (myValue) {     myValue = myValue.trim();     CKEDITOR.instances['idofeditor'].insertText(myValue); }; 
like image 135
Devjosh Avatar answered Sep 19 '22 14:09

Devjosh


CKEditor itself has a mechanism to insert text. If you update the textarea directly you are in effect bypassing some of the mechanisms CKEditor has to keep track of what text has been entered. Try this:

CKEDITOR.instances.IDofEditor.insertText('some text here'); 

More information here

like image 35
Rory McCrossan Avatar answered Sep 20 '22 14:09

Rory McCrossan