Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace selected content in the ckEditor with new content using javascript

I am using CKEditor ver.3.6 in my MVC Application.

My requirement is to update the selected text with new text in the ckEditor. I could find out the method editor.getSelection().getSelectedText(); for getting selected text from the editor. I need to add some tag with the selected text when a toolbar button is pressed and update the selected content using javascript.

For Example :

Content in the ckEditor is

 <span>Edit content in the editor</span>

and I have selected the word “editor” from ckEditor. I have to update the selected word “editor” with “ckEditor” using javascript code.

Please suggest a proper solution.

like image 361
Jayaraj Avatar asked Jan 09 '12 09:01

Jayaraj


People also ask

How to replace text in CKEditor?

to invoke the search panel and find and replace desired words or phrases or use the Ctrl / Cmd + F keyboard shortcut.

What is CKEditor replace?

The CKEditor 4 Find and Replace feature allows for finding and replacing any text in the editor easily. It helps the user find words, word parts or phrases matching the case of the searched text, which is especially helpful in lengthy documents and one that may utilize certain words in different contexts.

How do I get CKEditor content?

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


3 Answers

Use this function in the onclick event of a button.

function Replace()
 {
  //after selecting the text in the editor
  //get text to replace;    
  var repStr=$("#repTxt").val();        
  editor.insertHtml(repStr);    
 }

Cheers Sunil Raj

like image 137
Sunil Raj Avatar answered Oct 19 '22 18:10

Sunil Raj


It looks to me from the docs as the following would work (untested):

editor.insertText("ckEditor");
like image 30
Tim Down Avatar answered Oct 19 '22 17:10

Tim Down


Both editor.insertText() and editor.insertHtml() should work, but you have to make sure the editor is ready before you attempt to update the text:

var editor = CKEDITOR.replace('editor');

editor.on('instanceReady', function(){
    editor.insertHtml('...');
});
like image 35
Shlomi Nissan Avatar answered Oct 19 '22 16:10

Shlomi Nissan