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.
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);
    }
}
                        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;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With