Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text before and after selection in textarea with javascript

Tags:

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.

like image 492
Riccardo Avatar asked Jan 17 '11 14:01

Riccardo


2 Answers

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);
    }
}
like image 154
Simon Avatar answered Nov 09 '22 00:11

Simon


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;
like image 39
Matschie Avatar answered Nov 09 '22 01:11

Matschie