Posted By

jamesming on 09/15/08


Tagged

textarea


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

m00min
sulfurito
blueboy
Corncrib


How to replace selected textarea value using javascript


 / Published in: JavaScript
 

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

  1. // code for IE
  2. var textarea = document.getElementById("textarea");
  3.  
  4. if (document.selection)
  5. {
  6. textarea.focus();
  7. var sel = document.selection.createRange();
  8. // alert the selected text in textarea
  9. alert(sel.text);
  10.  
  11. // Finally replace the value of the selected text with this new replacement one
  12. sel.text = '<b>' + sel.text + '</b>';
  13. }
  14.  
  15.  
  16.  
  17.  
  18. // code for Mozilla
  19.  
  20. var textarea = document.getElementById("textarea");
  21.  
  22. var len = textarea.value.length;
  23. var start = textarea.selectionStart;
  24. var end = textarea.selectionEnd;
  25. var sel = textarea.value.substring(start, end);
  26.  
  27. // This is the selected text and alert it
  28. alert(sel);
  29.  
  30. var replace = '<b>' + sel + '<b>';
  31.  
  32. // Here we are replacing the selected text with this one
  33. textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: blueboy on July 22, 2009

This helped me out quite a bit, thanks.

You need to login to post a comment.