Return to Snippet

Revision: 8337
at September 15, 2008 14:04 by jamesming


Initial Code
// code for IE
var textarea = document.getElementById("textarea");

if (document.selection)
			{
				textarea.focus();
				var sel = document.selection.createRange();
                                // alert the selected text in textarea
				alert(sel.text);

                               // Finally replace the value of the selected text with this new replacement one
				sel.text = '<b>' + sel.text + '</b>';
			}




// code for Mozilla

  var textarea = document.getElementById("textarea");

  var len = textarea.value.length;
   var start = textarea.selectionStart;
   var end = textarea.selectionEnd;
   var sel = textarea.value.substring(start, end);

   // This is the selected text and alert it
   alert(sel);

  var replace = '<b>' + sel + '<b>';

  // Here we are replacing the selected text with this one
 textarea.value =  textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);

Initial URL
http://corpocrat.com/2008/08/10/how-to-get-selected-value-in-textarea-using-javascript/

Initial Description

                                

Initial Title
How to replace selected textarea value using javascript

Initial Tags

                                

Initial Language
JavaScript