Riccardo
Riccardo

Reputation: 2216

Insert text before and after the selection in a textarea with JavaScript

How can I insert text before and after the selection in a textarea with JavaScript?

Selection occurs into a textarea field of an HTML form.

Upvotes: 6

Views: 8193

Answers (2)

Simon
Simon

Reputation: 71

Her us a simple script that works in both Internet Explorer, Firefox, and Chrome, where myField is a object reference. It was assembled by several scripts found through the web.

function insertAtCursor(myField, myValueBefore, myValueAfter) {

    if (document.selection) {

        myField.focus();
        document.selection.createRange().text = myValueBefore + document.selection.createRange().text + myValueAfter;

    } else if (myField.selectionStart || myField.selectionStart == '0') {

        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValueBefore + myField.value.substring(startPos, endPos) + myValueAfter + myField.value.substring(endPos, myField.value.length);
    }
}

Upvotes: 7

Matschie
Matschie

Reputation: 1247

Try the following:

var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";

If you want to search and replace, then the following code will do the trick (in non-Internet Explorer browsers):

var textBeforeSelection = yourTextarea.value.substr(0, yourTextarea.selectionStart);
var textAfterSelection = yourTextarea.value.substr(yourTextarea.selectionEnd, yourTextarea.value.length);
yourTextarea.value = textBeforeSelection + " new selection text " + textAfterSelection;

Upvotes: 7

Related Questions