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.
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.
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; 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); } } myField.focus(); myField.selectionStart = startPos + myValueBefore.length; myField.selectionEnd = endPos + myValueBefore.length; insert this code inside the 'if else' condition at the end.