View Full Version : inserting text in Rich Text Editor via DOM

08-13-2004, 07:43 PM
Hi , I am messing with the Rich Text Editor from http://www.kevinroth.com/rte/demo.htm

its does most of the things I want , however I want to be able to add a string of text at the current cursor position , in IE
obj.document.execCommand('paste', false, '{whatever}');
works (as does insertHTML) but neither work in Moz for, I gather, security reasons (so perhaps may not even work in IE in SP2?), so how would I go about inserting a string of text in the editor ?

the function I have that gets the cursor position or range is ..

function add_template(rte,string_text){
var oRTE;
//get current selected range
if (document.all) {
oRTE = frames[rte];
var selection = oRTE.document.selection;
if (selection != null) {
rng = selection.createRange();
} else {
oRTE = document.getElementById(rte).contentWindow;
var selection = oRTE.getSelection();
rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
//works in IE//
oRTE.document.execCommand('paste', false,string_text);

so is there a way / what is the way ;) of perhaps adding the text via the DOM ?

Willy Duitt
08-13-2004, 10:09 PM
Try this:

<script type="text/javascript">
function setCaret (textObj) {
if (textObj.createTextRange) {
textObj.caretPos = document.selection.createRange().duplicate();
function insertAtCaret (textObj, textFeildValue) {
if (textObj.createTextRange && textObj.caretPos) {
var caretPos = textObj.caretPos;
caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?textFeildValue + ' ' : textFeildValue;
textObj.value = textFeildValue;
var rangeStart = textObj.selectionStart;
var rangeEnd = textObj.selectionEnd;
var tempStr1 = textObj.value.substring(0,rangeStart);
var tempStr2 = textObj.value.substring(rangeEnd);
textObj.value = tempStr1 + textFeildValue + tempStr2;
alert("This version of Mozilla based browser does not support setSelectionRange");


<form id="form1" action="" onsubmit="" method="post" enctype="text/plain">
<textarea name="tarea" rows="" cols="" style="width:300px;height:120px;"
onkeyup="setCaret(this);" >
Click in this textObj anywhere and then press the button below.
It will insert the text at the caret position.</textarea>
<input type="text" name="textfield" style="width:220px;" value="Mozilla 1.4"/>
<input type="button" value="insert at caret"


08-14-2004, 05:58 AM
Hey Willy , cheers for that ,

You have solved one of my problems as I also have to have a plain text-area based version which your code works a beaut for !

but for the RTE itself the working area is actually an iframe not a textarea so the code does not work for that.

still head scratching :D

08-14-2004, 06:39 AM
aha solved ! , googled around and found another revision of the RTE & this works ..

var tpl = document.createTextNode(strText);

so now its working in both ! , cheers again