tags:

views:

1302

answers:

3

I have a textArea and a list. When a user double clicks a list item, the label of the selected item should be inserted into the textarea. When a text is selected in the textArea, it should be replaced, otherwise the text just needs to be inserted into the existing text at the caret point.

I've managed to get the text and everything, I just can't manage to insert it at the caret point. Does anyone know how to do this?

A: 

You can use txtarea.selectionStart and txtarea.selectionEnd to get Selected text position.

After that, You delete txt and add new selected text.

I don't known much about Javascript, so I wrote it for U.

You can search on google with keywords: "Javascript Selected Text TextArea" "Javascript add text at position"

Sample code: function insertAtCursor(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; }

caretPos = doGetCaretPosition(myField);
alert(caretPos);
setCaretPosition(myField,caretPos-3);

}

+1  A: 

It's actually not JavaScript but Adobe Flex 3. Thanks for the help though, it did push me in the right direction. This is the way its done in Flex 3:

var caretStart:int = textArea.selectionBeginIndex;
var caretEnd:int = textArea.selectionEndIndex;
textArea.text = textArea.text.substring(0,caretStart)
              + newText
              + textArea.text.substr(caretEnd);
Maurits de Boer
Ever figure out a way to do this without losing HTML from existing text? I am pretty sure that the snippet above will strip existing HTML if there was any.
Ian Patrick Hughes
Nevermind. I just figured out a way. I'll post it below...
Ian Patrick Hughes
A: 

The accepted answer works great if you do not have existing HTML formatting. In my case, I inserted a new button into the editor that the user could click to put in a key word. I kept losing all HTML formatting until I dug around in the actual class and sided with a TextRange object:

       public function keyWord_Click(event:Event) : void 
        {

            var caretStart:int = txtEditor.textArea.selectionBeginIndex;
            var caretEnd:int = txtEditor.textArea.selectionEndIndex;
            var newText : String = "[[[KEYWORD]]]";

            var tf:TextRange = new TextRange(txtEditor,true,caretStart,caretEnd);
            tf.text = newText;

        }

The nice thing about this approach is, you can also apply conditional formatting to that TextRange object as needed.

Ian Patrick Hughes