views:

1696

answers:

2

How do I edit the selected text of a textarea form element?

EDIT: as in edit it in-place, replacing the orignal text.

+1  A: 

As a starting point, you can use this to get the selected text on the page:

function getSelectedText(){ 
    if(window.getSelection){ 
        return window.getSelection().toString(); 
    } 
    else if(document.getSelection){ 
        return document.getSelection(); 
    } 
    else if(document.selection){ 
        return document.selection.createRange().text; 
    } 
}
karim79
Note, this returns the text selected in the document, but didn't work for me in the textarea.
altCognito
+6  A: 

This works:

function replaceIt(txtarea, newtxt) {
  $(txtarea).val(
        $(txtarea).val().substring(0, txtarea.selectionStart)+
        newtxt+
        $(txtarea).val().substring(txtarea.selectionEnd)
   );  
}

replaceIt($('textarea')[0], 'fun')
altCognito