6

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.

1
  • Do you need broad browser support or will the modern browsers suffice (in other words, no IE at least until 9 comes out)? Commented Jan 17, 2011 at 14:42

2 Answers 2

7

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; 
Sign up to request clarification or add additional context in comments.

4 Comments

You'll need to do something else for IE if you want to support it.
I think the sample above will replace the whole textarea content... maybe there's a way to search & replace?
If you want to search + replace then you could just read the text until the selection and then the one until the end. I will edit the abov answer to show you exactly what I mean.
@Riccardo: No, jQuery doesn't handle this, although there are jQuery plug-ins that do.
7

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); } } 

2 Comments

However it doesn't place the cursor after the closing tags when it's done.
For those who are looking for to focus the caret inside the textarea, myField.focus(); myField.selectionStart = startPos + myValueBefore.length; myField.selectionEnd = endPos + myValueBefore.length; insert this code inside the 'if else' condition at the end.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.